How to return a value of three ways JAVA multi-threaded multi-threaded implementation

Tasks can return values ​​must implement the Callable interface is similar, and no return value tasks must be Runnable interface. 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, combined with the thread pool ExecutorService interfaces can be achieved legends have returned results multithreading. The following provides a complete multi-threaded test case has returned results

 

JAVA multi-threaded implementation there are three: inheritance Thread class that implements Runnable interface, 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, with only the last one is the return value.

 

1, inheritance Thread class implements multithreading
inheritance Thread class method even though I was classified as a multi-threaded implementation, but also on the nature of Thread implements an instance of Runnable interface, which represents an instance of the thread, and the thread start the only way is to start () method of the Thread class instance through. 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. E.g:

the MyThread the extends the Thread class {public
  public void RUN () {
   System.out.println ( "MyThread.run ()");
  }
}
start threads in the right place as follows:
the MyThread myThread1 the MyThread new new = ();
the MyThread = new new myThread2 the MyThread ();
myThread1.start ();
myThread2.start ();

2, implement Runnable multithreaded manner
if their class already extends another class, can not be directly extends the Thread, time, must implement a Runnable interface, as follows:
public class extends the MyThread OtherClass the implements Runnable {
  public void RUN () {
   System.out.println ( "MyThread.run ()");
  }
}
in order to start MyThread, you need to instantiate a Thread, and pass their MyThread example:
MyThread new new MyThread myThread = ();
the Thread the Thread Thread new new = ( myThread);
Thread.start ();
in fact, after passing a parameter to Runnable target Thread, Thread's run () method is called target.run (), refer to the source JDK:
public void run () {
  iF (! target = null) {
   target.run ();
  }
}

3, using ExecutorService, Callable, Future have realized returns the result of multi-threaded
ExecutorService, Callable, Future function of this object is actually belong to the class Executor framework. Want to learn more about Executor framework can access http://www.javaeye.com/topic/366591, where the face of the frame made a very detailed explanation. Return result is a new thread feature introduced in JDK1.5, indeed very practical, with this feature I do not need to in order to get the return value and struggling, and it may even achieve the loopholes.
Tasks can return values must implement the Callable interface is similar, and no return value tasks must be Runnable interface. 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, 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 show as below:

* the java.util.concurrent Import;.
Import java.util.Date;
Import java.util.List;
Import of java.util.ArrayList;

/ **
* return value with a thread
* /
@SuppressWarnings ( "an unchecked")
public class {the Test
public static void main (String [] args) throws ExecutionException,
InterruptedException {
System.out.println ( "program starts to run ---- ----");
a Date = new new date1 a Date ();

int. 5 = taskSize ;
// 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 + "");
// Get task and objects Future
F = pool.submit Future (C);
// System.out.println ( ">>>" + f.get () toString ().);
List.add (F);
}
// close thread pool
pool. the shutdown ();

// get all concurrent tasks run results
for (Future F: List) {
// get task from the Future object return value 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 {
} } Code Description: above Executors class code, a first series of thread pool factory method for creating, return are implemented thread pool 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.

Reference: three ways to achieve multi-threaded JAVA

Guess you like

Origin www.cnblogs.com/aspirant/p/11734406.html