Melted down re-creation of multi-threading

Source: Internet
Author: User
Tags thread class

Four ways of creating:

1. How to create and start multithreading by inheriting the thread class

2. How to create and start threads by implementing the Runnable interface

3. How to create and start threads by implementing the callable interface

4. Summarize the ways in which threads are created in Java, comparing their strengths and differences

First, inherit the thread class to create a threading class

Java uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses, each of which performs a certain task, in effect executing a program flow in a sequential code. The steps to create and start multithreading in Java by inheriting the thread class are as follows:

  1. Define a subclass of the thread class and override the run () method of the class, which represents the task that the thread needs to complete

So the run () method is called the thread execution body

2. Create an instance of the thread subclass, that is, the threading object is created

3. Call the Start () method of the thread object to start the thread

code example:
//inheriting the thread class to create threads Public classThreadcreatextendsthread{//Thread Execution Methods@Override Public voidrun () { for(inti = 0; I < 2; i++) {
Gets the current thread name can be used with this System.out.println ( This. GetName ()); } } Public Static voidMain (string[] args) { for(inti = 0; I < 2; i++) {System.out.println ("This is the main thread" +Thread.CurrentThread (). GetName ()); if(i==1){ //Create a thread Newthreadcreat (). Start (); //Create a second thread Newthreadcreat (). Start (); } } }}

Operation Result:

First run Result: Second run result:

Here is the main thread main here is main thread main

Here is the main thread main here is main thread main

Thread-0 Thread-0
Thread-1 Thread-0
Thread-1 Thread-1
Thread-0 Thread-1

The program no matter how many times the output of the record number is certain, altogether is 6 records. The main thread executes a for loop to print 2 records, two sub-threads Print 2 records, 6 records in total. Because the I variable is an instance property of Threadcreat, not a local variable, because the program needs to create a Threadcreat object each time the thread object is created , So Thread-0 and Thread-1 cannot share this instance property, so each thread will execute 2 loops.

Second, realize runnable interface

1. Define the implementation class for the Runnable interface, and override the run () method of the interface, which is also the thread-executing body of the run () method

2. Create an instance of the Runnable implementation class, and use this instance as the target of the thread to create the thread object, which is the true thread object

3. Call the Start () method of the thread object to start the thread

The Runnable object is only used as the thread execution body as the run () method contained in the Target,runnable implementation class of the thread object only. The actual thread object is still the thread instance, except that the thread thread is responsible for executing its target's run () method

code example:   

Implementing the Runnable Interface creation thread
public class Threadcreat implements runnable{

private int i;
void print () {
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
}
The Run method is also the thread execution body
public void Run () {
for (; i < 2; i++) {
When the thread class implements the Runnable interface,
If you want to get the current thread, you can only use the Thread.CurrentThread () method.
Print ();
}
}
public static void Main (string[] args) {
for (int i = 0; i < 2; i++) {
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
if (i = = 1) {
Threadcreat st = new Threadcreat ();
Create a new thread by using the new thread (target, name) method
New Thread (St, "1"). Start ();
New Thread (St, "2"). Start ();
}
}
}
}

First execution Result:

main,0 main,0

main,1 main,1
New thread -1,0 new thread -1,0
New thread -1,1 new thread -1,1

New Thread -2,0

From the running results we can see that the output of the console is out of order, and each result is different. This is because:
  1. In this way, the Runnable object created by the program is only the target of the thread, and multiple threads can share the same target.

2. So multiple threads can share instance properties of the same thread class, the target class of a thread.

3. The process to print () output to the console window is not multithreaded security, and another thread can output it during one thread output.

 

Iii. creating threads using callable and future

Starting with Java 5, Java provides the callable interface, which looks like an enhanced version of the Runnable interface, and the callable interface provides a call () method that can be used as a thread execution body, but the call () method is more powerful than the run () method

The difference between the call method and the Run method:

1. The call () method can have a return value, and the Run method does not.

2. The call () method can declare an exception, and the Run method does not

The call () method also has a return value-----the call () method is not called directly, it is called as the thread execution body. So how do you get the return value of the call () method?

Overview of future interfaces

Java 5 provides a future interface to represent the return value of the call () method in the callable interface, and provides a Futuretask implementation class for the future interface that implements the The future interface and the Runnable interface can be used as the target of the thread class. In the future interface, several public methods are defined to control its associated callable tasks:

1. Boolcan Cancel (Boolean maylnterruptltrunning): Attempt to cancel the callable task associated with the future

2. V get (): Returns the return value of the call () method in the callable task. Calling this method will cause the program to block and must wait until the child thread ends to get the return value

3. V Get (Long timeout,timeunit unit): Returns the return value of the call () method in the callable task.

This method allows the program to block the time specified by timeout and unit at most, and if the callable task does not return a value after a specified time,

Timeoutexccption exception will be thrown

4. Boolean iscancelled (): Returns True if the callable task is canceled before it is properly completed

5. Boolean isDone (): Callable if the task is completed, returns true

Note: The callable interface has a generic limit, and the generic parameter type in the callable interface is the same as the call () method return value type.

To create and start a thread that has a return value

1. Create an implementation class for the callable interface and implement the call () method, which will act as the thread execution body, and the call () method has a return value

2. Create an instance of the callable implementation class and use the Futuretask class to wrap the callable object

The Futuretask object encapsulates the return value of the call () method of the Callable object

3. Create and start a new thread using the Futuretask object as the target of the thread object

4. Call the Get () method of the Futuretask object to get the return value after the child thread finishes executing

code example:

 Public classMycallabletestImplementsCallable<integer>{    //implement the Call method as the thread execution body     PublicInteger Call () {inti = 0;  for(; i < i++;) {System.out.println (Thread.CurrentThread (). GetName ()+ "\ T" +i); }        //The call () method can have a return value        returni; }     Public Static voidMain (string[] args) {//Create a Callable objectMycallabletest mycallabletest =Newmycallabletest (); //use Futuretask to wrap callable objectsfuturetask<integer> task =NewFuturetask<integer>(mycallabletest);  for(inti = 0; I < 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "\ T" +i); if(i = = 20){                //in essence, create and start a thread with a callable object                NewThread (Task, "callable")). Start (); }        }        Try{            //get thread return valueSystem.out.println ("Callable return value:" +task.get ()); }        Catch(Exception ex) {ex.printstacktrace (); }    }}

Run the above program and you will see the alternate execution of the thread represented by the main thread and the call () method, and finally the return value of the call () method will be output by the program. There is not much difference between creating a callable implementation class in the above program and creating a Runnable implementation class, except that the call () method of callable allows the declaration to throw an exception, and the return value is allowed. When the loop variable I equals 20 o'clock in the main thread, the program starts the thread that futuretask the object as target. The program finally calls the get () method of the Futuretask object to return the return value of the call () method, which causes the main thread to be blocked until the call () method ends and returns.

Melted down re-creation of multi-threading

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.