Two ways to create threads in Java

Source: Internet
Author: User
Tags ticket

Java provides threading class thread to create multithreaded programs. In fact, creating a thread is the same as creating an object of a normal class, and a thread is an instance object of the thread class or its subclasses. Each thread object describes a separate thread. To produce a thread, there are two ways of doing it:

You need to derive a new thread class from the Java.lang.Thread class, overloading its run () method;
Implement the Runnalbe interface, overloading the run () method in the Runnalbe interface.

  Why should Java provide two ways to create threads? What are the differences between them? In comparison, which method is better?

  In Java, a class only supports single inheritance, that is, when a new class is defined, it can only extend one external class. This way, if the custom thread class is created by extending the thread class, then the custom class cannot extend the other classes. It is not possible to implement more complex functions. Therefore, if your custom class must extend other classes, you can define the class as a threading class by using a method that implements the Runnable interface, which avoids the limitations of Java single inheritance.

It is also important that threads created with the implementation of the Runnable interface can handle the same resource, thus sharing resources.

1. Create multithreading by extending the thread class

Suppose a cinema has three ticket outlets for ticketing for children, adults and the elderly, respectively. The cinema has 100 movie tickets for each window, namely children's, adult and senior. Three windows need to sell tickets at the same time, and now there is only one conductor, the conductor is equivalent to a CPU, three Windows is equivalent to three threads. The program looks at how to create these three threads.

1 public class Mutlithreaddemo {2 publicly     static void main (string[] args) {3         mutlithread m1=new mutlithread ("Wind ow 1 ");  4         mutlithread m2=new mutlithread ("Window 2");  5         mutlithread m3=new mutlithread ("Window 3");  6         M1.start (); 7         M2.start (); 8         M3.start (); 9     }10}
1 public class Mutlithread extends thread {2     private int ticket=100;//Each thread has 100 tickets  3  4     Public Mutlithread () {} 5 public     mutlithread (String name) {6         super (name); 7     } 8      9     @Override10     public void Run () {One while         (ticket>0) {             System.out.println (ticket--+ "was saled by" + Thread.CurrentThread (). GetName ());     }15}

A thread class is defined in the program, which extends the thread class. The extended thread class is used to create three thread objects in the main method of the Mutlithreaddemo class and to start them separately through the start () method.

As you can see from the results, each thread corresponds to 100 movie tickets, and there is no relationship between them, which means that each thread is equal, has no priority relationship, and therefore has the opportunity to get CPU processing. But the result

Show that these three threads are not executed alternately, but in the case of three threads being executed simultaneously, some threads are given more chances to allocate time slices, the tickets are sold out in advance, and some threads are compared by the chance to allocate time slices

Less, the tickets are sold out later.

  It can be seen that multiple threads created with the extended thread class, although executing the same code, are independent of each other and have their own resources, without interfering with each other.

2. Create multithreading by implementing the Runnable interface

1 public class Mutlithreaddemo {2 publicly     static void main (string[] args) {3         mutlithread m1=new mutlithread ("Wind ow 1 ");  4         mutlithread m2=new mutlithread ("Window 2");  5         mutlithread m3=new mutlithread ("Window 3");  6         Thread T1=new thread (m1);  7         thread t2=new thread (m2);  8         Thread t3=new thread (m3);  9         T1.start ();         T2.start ();         T3.start ();     }13}
1 public class Mutlithread implements runnable{  2     private int ticket=100;//Each thread has 100 tickets  3     private String name;  4     mutlithread (String name) {  5         this.name=name;  6     }  7 public     Void Run () {  8 while         (ticket>0) {  9             System.out.println (ticket--+ "Is saled by" +name); Ten}     12}

Since the three threads are independent of each other and have their own resources, i.e. 100 movie tickets, the output of the program is similar to the 1 results. are the respective threads of their own 100 tickets for separate processing, non-impact.

Visible, as long as the reality of the situation requires that new threads are independent of each other, each with resources, and do not interfere with each other, which way to create multi-threading is possible. Because multi-threaded threads created in both ways can achieve the same functionality.

3, through the implementation of runnable interface to achieve the sharing of resources between threads

In reality, there are situations, such as simulating a train station ticketing system, if the day from A to B to the train ticket only 100, and allow all windows to sell the 100 tickets, then each window is equivalent to a thread, But the difference between this and the previous example is that all the threads are working on the same resource, which is 100 tickets. If you are still using the previous method to create a thread that is obviously impossible to implement, how do you deal with this situation? Look at the following program, the program code is as follows:

1 public class Mutlithreaddemo {2 public     static void Main (string[] args) {3         mutlithread m=new mutlithread (); 
   
    4         thread t1=new thread (m);  5         thread t2=new thread (m);  6         thread t3=new thread (m);  7         T1.start ();  8         T2.start ();  9         T3.start ();     }11}
   
1 public class Mutlithread implements runnable{2     private int ticket=100;//Each thread has 100 tickets 3 public     void Run () {4
   
    while (ticket>0) {5             System.out.println (ticket--+ "is saled by" +thread.currentthread ()); 6}         7     } 8}
   

The result, as previously analyzed, is that the program creates only one resource in memory, and the new three threads are based on access to the same resource, and because the same code is running on each thread, they perform the same function.

It can be seen that if a real-world problem requires that multiple threads be created to perform the same task, and that the same resource will be shared among the multiple threads, the multithreaded program could be created in a way that implements the Runnable interface. This functionality is not possible by extending the thread class, and the reader wants to see why.

  The implementation of the Runnable interface has unparalleled advantages over the extended thread class. This approach is not only beneficial to the robustness of the program, so that the code can be shared by multiple threads, and the code and data resources are relatively independent, which is particularly suitable for multiple threads with the same code to handle the same resource situation. In this way, the thread, code and data resources are effectively separated, which embodies the idea of object-oriented programming. As a result, almost all multithreaded programs are done by implementing the Runnable interface.

Transferred from: http://www.cnblogs.com/gw811/archive/2012/10/15/2724882.html

Two ways to create threads in Java

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.