"java concurrent programming" Vi: runnable and thread implementation of multithreading differences (including Code)

Source: Internet
Author: User
Tags ticket

Reprint Please specify source:http://blog.csdn.net/ns_code/article/details/17161237


There are two ways to implement multithreading in Java: inherit the thread class, implement the Runnable interface, in the program development as long as the multi-threaded, definitely always to implement the Runnable interface mainly, because the implementation of runnable interface compared to inherit the thread class has the following advantages:

1, can avoid the Java single inheritance characteristics brought about by the limitations;

2, enhance the robustness of the program, code can be shared by multiple threads, code and data is independent;

3. Suitable for multiple threads with the same program code to handle the same resource Situation.


The following is an example of a typical ticket purchase procedure (which is basically the Case) to illustrate the difference between the Two.

First by inheriting the thread class implementation, the code is as Follows:

[java]View PlainCopy
  1. Class MyThread extends thread{
  2. private int ticket = 5;
  3. public void run () {
  4. for (int i=0;i<10;i++)
  5. {
  6. if (ticket > 0) {
  7. System.out.println ("ticket =" + ticket--);
  8. }
  9. }
  10. }
  11. }
  12. Public class threaddemo{
  13. public static void main (string[] Args) {
  14. new MyThread (). start ();
  15. new MyThread (). start ();
  16. new MyThread (). start ();
  17. }
  18. }
the results of a certain execution are as Follows:

As can be seen from the results, each thread sold 5 tickets separately, that is, to complete the task of buying tickets independently, but in practical applications, such as railway station ticketing, need multiple threads to work together to complete the task, in this case, multiple threads together buy 5 Tickets.

The following is a multithreaded program implemented by implementing the Runnable interface, with the following code:

[java]View PlainCopy
  1. Class MyThread implements runnable{
  2. private int ticket = 5;
  3. public void run () {
  4. for (int i=0;i<10;i++)
  5. {
  6. if (ticket > 0) {
  7. System.out.println ("ticket =" + ticket--);
  8. }
  9. }
  10. }
  11. }
  12. Public class runnabledemo{
  13. public static void main (string[] Args) {
  14. MyThread my = new MyThread ();
  15. new Thread (my). start ();
  16. new Thread (my). start ();
  17. new Thread (my). start ();
  18. }
  19. }
The results of a certain execution are as Follows:


As can be seen from the results, three threads sold a total of 5 tickets, that they jointly completed the task of buying tickets, to achieve the sharing of Resources.


add three points for the above code:

1. In the second method (Runnable), the order of ticket output is not 54321, because the timing of thread execution is unpredictable, and Ticket--is not an atomic Operation.

2, in the first method, we new 3 thread objects, that is, three threads execute the code in three objects, so it is three threads to complete the task of selling tickets independently, and in the second method, we also new 3 thread objects, but only one runnable object, 3 thread objects share the code in this runnable object, so there will be 3 threads that work together to complete the result of the sell ticket Task. If we new out 3 runnable objects, passing in 3 thread objects as arguments, then 3 threads will execute the code in their respective runnable objects independently, i.e. 3 threads sell 5 Tickets RESPECTIVELY.

3, in the second method, because 3 thread objects together execute a Runnable object in the code, it may cause thread insecurity, such as may ticket output 1 (if we system.out .... Statement before the thread hibernation operation, which is likely to occur, this situation is due to a thread after judging ticket as 1>0, there is no time to subtract 1, another thread has ticket minus 1, changed to 0, then the next thread will ticket minus 1, Then got-1. 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.

"java concurrent programming" Vi: runnable and thread implementation of multithreading differences (including Code)

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.