Java multithreaded Programming--How to start a thread

Source: Internet
Author: User

How to start a thread 1. How Java multithreading is implemented 1.1 Inheriting the thread classThe definition classes are as follows:
Public Subthread extends Thread {     @override public     void Run () {         ...     }}
When used:
Thread subthread = new Subthread (); Subthread.start ();
You can use functions already in the thread class to operate.
1.2 Implement the Runnable interface definition class as follows:
Public Subthread implements Runnable {public    void run () {    //dosomething ...    }}
When used:
Subthread subthread = new Subthread (); Thread thread = new Thread (subthread); Thread.Start ();
The class implemented in this way is actually a generic class, except that it implements the thread's Run method, and therefore registers it in the object of the thread class to run as a thread. The 1.3 implementation of the Callable interface class is defined as follows:
Public Subthread implements callable<string> {public    String call () {        //do Something ...    }}
As you can see, threads implemented in this way carry a return value, callable<string>Specifies the return value type, and callable can throw an exception, while runnable cannot. Also, looking at the thread class will find that the thread class and directly support callable, so callable to work well with other classes. There are several ways to support callable, which only write one of their own tests, and so on.
(1) with Futuretask
Futuretask<v> implements the Runnable interface and the future interface (futur can get the return value of an asynchronous thread execution), so you can use Futuretask to implement the start thread and get the results of the thread execution. Examples are as follows:
public class Testcallable implements callable<string> {public    String call () throws Interruptedexception {        Thread.Sleep (the);        Return "Call return";    }    public static void Main (string[] args) {        testcallable test = new testcallable ();        futuretask<string> futrue = new futuretask<string> (test);        Thread thread = new Thread (futrue);        Thread.Start ();        Before you need the results, you can sit on other things        System.out.println ("Hello");        try {            System.out.println (Futrue.get ());        } catch (Executionexception e) {            System.out.println (" Error executing callable ");        } catch (Interruptedexception e) {            System.out.println ("Error executing callable");        }        System.out.println ("concluding Remarks");}    }


Output Result:
Hellocall return concluding remarks

As you can see, before we can use the execution result of a child thread, we may sit on something else and, when needed, call the future's Get () method to get the execution result of the child thread. Note that the Get () method of the future is blocked until the child thread execution ends. Of course, we can use the get (long timeout, timeunit unit) function to specify the wait time.
(2) TODO mates ExecutorserviceThrough the executorservice of the Submit method can be executed callable, for the thread pool this piece temporarily not much understanding, follow up their own practice after the addition ^ ^. 2. SummaryStarting with the thread class, you can see that the extends thread and implements Runable are the most basic way to implement a thread, and futuretask these are implemented on the cornerstone of Runnable, Callable must rely on other classes that support it to execute, or it will not have a half-dime relationship with the thread. It is very helpful to understand the usage of some high-level, otherwise it is not known why. Just like if you do not know the TCP protocol, in the Java network programming, for some strange phenomenon, you do not know is the underlying protocol, or Java itself for the same reason ... Pull away
The choice of the above-mentioned options, in fact, as needed: The advantage of extends thread is that you can directly use the parent thread to provide you with the method of threading, and the disadvantage is that the Java class does not support multiple inheritance, so it may not be so free to use. The advantage of implements Runnable is that you can implement many other interfaces, you can inherit other classes, the degree of freedom is greatly improved, and the disadvantage is the operation of the thread, it takes a little thought ^ ^. In relation to inheriting the thread class, it is recommended to implement runnable, so that the program is more extensible. The advantage of implements callable is that it can return thread execution results and throw exceptions, which is useful for scenarios where the execution results of other threads are to be used.




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

Java multithreaded Programming--How to start a thread

Related Article

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.