Four ways to achieve multi-threaded

Java multi-threaded implementation, there are four: the Thread class inheritance, implement Runnable, implement Callable interface to create Thread by thread FutureTask wrapper, use ExecutorService, Callable, Future have realized returns the result of multi-threading.

The first two ways in which the threads are not after the implementation of the return value, the latter two with a return value.



1, inheritance Thread class to create threads
on the Thread class is essentially implements an instance of Runnable interface, representing an instance of a thread. The only way to start the thread is () instance method by start Thread class. start () method is a native method, it will start a new thread, and executes run () method. This is very simple way to achieve multi-threaded, through their classes directly extend Thread, and replication run () method, you can start a new thread and execute the run () method define yourself. For example:

copy the code
public the MyThread the extends the Thread class {  
  public void RUN () {  
   System.out.println ( "MyThread.run ()");  
  }  
}  

the MyThread myThread1 the MyThread new new = ();  
the MyThread myThread2 the MyThread new new = ();  
myThread1 .start ();  
myThread2.start ();  
copy the code
2, to achieve Runnable interface to create threads
If their class already extends another class, you can not be directly extends the Thread, at this time, a Runnable interface may be implemented as follows:

public class extends the MyThread OtherClass the implements Runnable {  
  public void RUN () {  
   System.out.println ( "the MyThread. RUN () ");  
  }  
}  
in order to start MyThread, need to instantiate a Thread, and pass their MyThread example:

MyThread new new MyThread myThread = ();  
the Thread Thread new new = the Thread (myThread);  
Thread.start ();  
in fact, when a Runnable target parameter passed to the Thread, the Thread run () method is called target.run (), refer to the source JDK:

public void run () {  
  iF (! target = null) {  
   target. RUN ();  
  }  
}  
. 3, implement Callable interface to create a thread by thread FutureTask wrapper

Callable Interface (one way only) is defined as follows:   

public interface Callable <V> { 
  V call () throws Exception;} 
copy the code
public class SomeCallable <V> OtherClass the extends the implements a Callable <V> {

    @Override
    public V Call () throws Exception {
        // Generated Method Stub the TODO Auto-
        return null;
    }

}
copy the code
Copy codes
a Callable <V> = new new SomeCallable oneCallable <V> ();   
// Create a Callable <Integer> a FutureTask <Integer> objects:   
a FutureTask, <V> = new new oneTask a FutureTask, <V> (oneCallable);   
// NOTE: FutureTask <Integer> is a wrapper that is created by accepting Callable <Integer>, it also realized the Future and Runnable interface. 
  // Create a Thread object of a FutureTask, <Integer>:   
Thread oneThread = new new Thread (oneTask);   
oneThread.   
// At this point, a thread is created complete.
Copy the code
4, ExecutorService, Callable, Future returns the result achieved with a thread

ExecutorService, Callable, Future interfaces are actually three frame belongs Executor. Returns a result of introducing the new thread in JDK1.5, you do not need to have such a feature in order to obtain a return value struggling. And yourself achieving it may flawed.

Tasks can return values must implement the Callable interface. Similarly, the task no return value must implement Runnable.

After performing Callable task, you can get a Future object, call the get in on the object you can get to the return of the Object Callable task.

Note: get method is blocked, namely: no thread returns the result, get method will wait.

Combined with the thread pool ExecutorService interfaces can be achieved legends have returned results multithreading.

Here is an example of a multi-threaded complete test results have returned, verified under JDK1.5 had no problem can be used directly. Code is as follows:

copy the code
Import the java.util.concurrent *;.  
Import java.util.Date;  
Import java.util.List;  
Import of java.util.ArrayList;  
  
/ ** 
* returns a value thread 
* /  
@SuppressWarnings ( " unchecked ")  
the Test class {public  
public static void main (String [] args) throws ExecutionException,  
    InterruptedException {  
   System.out.println ( "program starts to run ---- ----");  
   a Date = new new date1 a Date ();  
  
   int taskSize = 5;  
   // Create a thread pool  
   ExecutorService = Executors.newFixedThreadPool the pool (taskSize);  
   // create a plurality of tasks have return values  
   List <Future> = new new List the ArrayList <Future> ();  
   for (int I = 0; I <taskSize; I ++) {  
    a Callable MyCallable new new C = (I + "");  
    // task and acquires the object Future  
    Future pool.submit = F (C);  
    // System.out.println ( ">>>" f.get + () toString ());.  
    List.add (F);  
   }  
   // close the thread pool  
   pool.shutdown ();  
  
   // get all concurrent tasks run results  
   for (Future F: List) {  
    // Get the return value from the task Future object, and outputs to the console  
    System.out.println ( ">>> "+ f.get () toString ());.  
   }  
  
   a Date = new new DATE2 a Date ();  
   System.out.println (" ---- ---- program finishes running, running time [ "  
     + (DATE2. getTime () - date1.getTime ()) + " ms]");  
}  
}  
  
class MyCallable the implements a Callable <Object> {  
Private String taskNum;  
  
MyCallable (String taskNum) {  
   this.taskNum = taskNum;  
}  
  
public Object Call () throws {Exception  
   System.out.println ( ">>>" + + taskNum "task starts");    
   Date dateTmp1 = new Date();  
   Thread.sleep (1000);  
   a Date = new new dateTmp2 a Date ();  
   Long Time = dateTmp2.getTime () - dateTmp1.getTime ();  
   System.out.println ( ">>>" taskNum + + "a task termination");  
   return taskNum + "running task returns a result, the current task time [" + time + "msec]";  
}  
}  
copy the code


Code Description:
above Executors class code, a series of methods for creating a thread pool facility, return thread pool have achieved ExecutorService interface.
public static ExecutorService newFixedThreadPool (int nThreads) 
thread pool that creates a fixed number of threads.
public static ExecutorService newCachedThreadPool () 
Creates a cached thread pool thread call to execute will reuse previously constructed (if the thread is available). If an existing thread is not available, a new thread is created and added to the pool. Terminate and remove those threads that have not been used for 60 seconds from the cache.
public static ExecutorService newSingleThreadExecutor () 
to create a single threaded Executor.
public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize) 
to create a thread pool to support regular and periodic task execution, can be used to replace the Timer class in most cases.

Providing ExecutoreService submit () method, passing a Callable a, or the Runnable, return Future. If the background thread pool Executor has not calculated the Callable completed, this call returns a Future object get () method will block until the calculation is complete.

Published 667 original articles · won praise 6 · views 9015

Guess you like

Origin blog.csdn.net/heima201907/article/details/104423361