Two ways to implement multithreading: inheriting the Thread class or implementing the Runnable interface

Source: Internet
Author: User
Tags ticket

Two ways to implement multithreading: inheriting the Thread class or implementing the Runnable interface

There are two ways to implement multithreading in Java: Inherit the thread class and implement the Runnable interface, in the program development as long as the multi-threading, we generally implement the Runnable interface, the reason is that the implementation of the interface is better than inheriting the class.

The first implementation of multithreading: inheriting the Thread class

Steps are as follows

  • Create a class that inherits the thread (assumed to be a) and overrides the thread's Run method
  • Constructs a Class A object, assumed to be AA
  • Call the Start method of the AA. (The Start method is inherited from thread.)

Specific examples are as follows

Package org.wrh.concurrent;/ * * Station multi-site ticket sales Process * */ class MyThread extends Thread{      Private intTicketnum =Ten; Public voidRun () { for(intI=0;i<Ten; i++) {if(Ticketnum >0) {System.out.println (Thread.CurrentThread (). GetName () +"is selling the first"+ ticketnum+"Ticket");            ticketnum--; }          }      }  } Public  class ThreadDemo01{       Public Static voidMain (string[] args) {/ * * A total of three thread objects, each threading the name of the thread * */Thread t1=NewMyThread (); T1.setname ("Thread A");       T1.start (); Thread t2=NewMyThread (); T2.setname ("Thread B");        T2.start (); Thread t3=NewMyThread (); T3.setname ("Thread C");     T3.start (); }  }

The results of the program run are as follows:

Thread A is selling the 10th ticket.
Thread B is selling the 10th ticket.
Thread A is selling the 9th ticket.
Thread B is selling the 9th ticket.
Thread A is selling the 8th ticket.
Thread B is selling the 8th ticket.
Thread C is selling the 10th ticket.
Thread C is selling the 9th ticket.
Thread C is selling the 8th ticket.
Thread C is selling the 7th ticket.
Thread C is selling the 6th ticket.
Thread C is selling the 5th ticket.
Thread C is selling the 4th ticket.
Thread C is selling the 3rd ticket.
Thread C is selling the 2nd ticket.
Thread C is selling the 1th ticket.
Thread A is selling the 7th ticket.
Thread A is selling the 6th ticket.
Thread A is selling the 5th ticket.
Thread A is selling the 4th ticket.
Thread A is selling the 3rd ticket.
Thread A is selling the 2nd ticket.
Thread A is selling the 1th ticket.
Thread B is selling the 7th ticket.
Thread B is selling the 6th ticket.
Thread B is selling the 5th ticket.
Thread B is selling the 4th ticket.
Thread B is selling the 3rd ticket.
Thread B is selling the 2nd ticket.
Thread B is selling the 1th ticket.

As can be seen from the results, a, B, c three threads each each thread sold independently of each other 10 tickets, but the actual train station ticket, is to need multiple threads to jointly sell n tickets.

Note :

  • The function of the Start method in thread is to create a new thread and automatically call the thread's Run method, and calling the Run method directly does not create a new thread.
  • Executing a thread is actually the code inside the Run method that executes the thread.
  • Executing the Aa.start () method does not mean that the corresponding thread of AA will be executed, but that the thread has the qualification to be executed immediately by the CPU. But because there are a lot of threads that want to preempt CPU execution, the CPU does not necessarily immediately execute the corresponding thread of AA. The execution of a thread is controlled by the operating system: priority, length of time, maximum wait time, and so on.
  • A thread object cannot call start () two times, or an exception will be thrown.
The second implementation of Multithreading: Implementing the Runnable Interface

The steps are as follows:

  • Defines a class that implements the Runnable interface, which is assumed to be a
  • To create a Class A object AA
  • Use AA to construct a thread object TT,Thread tt=new Thread(aa)
  • Call the Start method of TT: ' Tt.start ()
Package org.wrh.concurrent; class mythread_1 implements Runnable{      Private intTicketnum = -; Public voidRun () { for(intI=0;i<Ten; i++) {if(Ticketnum >0) {System.out.println (Thread.CurrentThread (). GetName () +"is selling the first"+ ticketnum+"Ticket");            ticketnum--; }          }      }  } Public  class ThreadDemo02{       Public Static voidMain (string[] args) {mythread_1 my =NewMythread_1 ();NewThread (My). Start ();NewThread (My). Start ();NewThread (My). Start (); }  }

The results of the program run as follows:

Thread-1 is selling the 20th ticket.
Thread-2 is selling the 20th ticket.
Thread-0 is selling the 20th ticket.
Thread-2 is selling the 18th ticket.
Thread-1 is selling the 19th ticket.
Thread-2 is selling the 16th ticket.
Thread-0 is selling the 17th ticket.
Thread-2 is selling the 14th ticket.
Thread-1 is selling the 15th ticket.
Thread-2 is selling the 12th ticket.
Thread-0 is selling the 13th ticket.
Thread-2 is selling the 10th ticket.
Thread-1 is selling the 11th ticket.
Thread-2 is selling the 8th ticket.
Thread-0 is selling the 9th ticket.
Thread-2 is selling the 6th ticket.
Thread-1 is selling the 7th ticket.
Thread-2 is selling the 4th ticket.
Thread-0 is selling the 5th ticket.
Thread-2 is selling the 2nd ticket.
Thread-1 is selling the 3rd ticket.
Thread-0 is selling the 1th ticket.

From the above results can be seen:

  • 1th: These three threads are not independent of each other to sell 20 tickets, but together to sell 20 tickets.
  • 2nd: These three threads sell tickets in the process of conflict, for example, all sell the 20th ticket,

The reason for the 2nd is:

A thread after judging ticketnum for 20>0, there is no time to lose 1, another thread at this point also Judge Ticketnum for 20>0, there is not a chance to reduce 1, then the third thread to start to perform the discovery Ticketnum or 20> 0, so three threads sold the 20th ticket 3 times. This requires the addition of a synchronous operation (that is, a mutex) to ensure that only one thread at a time performs the operation in each for loop. In the first approach, there is no need to join the synchronization operation because each thread executes the code in its own thread object, and there is no case where multiple threads are executing the same method together.

The following code is added to the synchronization operation:

Package org.wrh.concurrent; class mythread_1 implements Runnable{      Private intTicketnum = -; PublicSynchronizedvoidRun () { for(intI=0;i<Ten; i++) {if(Ticketnum >0) {System.out.println (Thread.CurrentThread (). GetName () +"is selling the first"+ ticketnum+"Ticket");            ticketnum--; }          }      }  } Public  class ThreadDemo02{       Public Static voidMain (string[] args) {mythread_1 my =NewMythread_1 ();NewThread (My). Start ();NewThread (My). Start ();NewThread (My). Start (); }  }

The above code is only in the original code based on the Run method with a synchronized keyword to limit the ability to complete the lock.
The results of the program are as follows:

Thread-0 is selling the 20th ticket.
Thread-0 is selling the 19th ticket.
Thread-0 is selling the 18th ticket.
Thread-0 is selling the 17th ticket.
Thread-0 is selling the 16th ticket.
Thread-0 is selling the 15th ticket.
Thread-0 is selling the 14th ticket.
Thread-0 is selling the 13th ticket.
Thread-0 is selling the 12th ticket.
Thread-0 is selling the 11th ticket.
Thread-2 is selling the 10th ticket.
Thread-2 is selling the 9th ticket.
Thread-2 is selling the 8th ticket.
Thread-2 is selling the 7th ticket.
Thread-2 is selling the 6th ticket.
Thread-2 is selling the 5th ticket.
Thread-2 is selling the 4th ticket.
Thread-2 is selling the 3rd ticket.
Thread-2 is selling the 2nd ticket.
Thread-2 is selling the 1th ticket.

A total of 20 tickets were bought, and each ticket sold only once, this is the realization of the function of the sync lock

Finally, the basic method of threading control is introduced.
(1) isAlive (): Determines whether the thread is still "alive", that is, whether the thread has not yet terminated
(2) getpriority (): Gets the priority value of the thread, and 0 indicates the highest priority of the thread.
(3) SetPriority (): Sets the priority of the thread
(4) Join (): Called with the Thread object, thread A will wait for thread B to execute after it finishes executing if another thread B's Join method is called in a thread A.
(5) Yield (): yields the CPU, and the current thread enters the ready queue for scheduling. Directly with the thread class call, yield yields the CPU execution to the same level of thread, and if no thread of the same level waits for the CPU to execute, the thread continues to execute

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Two ways to implement multithreading: inheriting the Thread class or implementing the Runnable interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.