After Java5, the concurrency thread has changed radically, and the most important thing is a new stack of APIs to start, schedule, and manage threads. After Java5, it is better to start the thread by executor turndown with the thread start (). In the new feature, it is easy to control the threading startup, execution, and shutdown processes, and it is easy to use the thread pool features.
first, create a taskA task is a class that implements the Runnable interface. The real run method is available when you create it.
II. Implementation of the mandate Executes the task through the Java.util.concurrent.ExecutorService interface object, which is created through a static method of the tool class java.util.concurrent.Executors. executors Factory and utility methods for the Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes defined in this package. executorservice provides methods for managing termination, as well as a way to generate a future for tracking one or more asynchronous task execution states. You can turn off Executorservice, which will cause it to stop accepting new tasks. When it is closed, the executing program terminates with no tasks executing, no tasks waiting to be executed, and new tasks cannot be submitted. Executorservice.execute (New testrunnable ()); 1, creating Executorservice is created by means of a static method java.util.concurrent.Executors the tool class. Executors factory and utility methods for the Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes defined in this package. For example, to create an instance of Executorservice, Executorservice is actually a management tool for a thread pool: Executorservice Executorservice = Executors.newcachedthreadpool (); Executorservice Executorservice = Executors.newfixedthreadpool (3); Executorservice Executorservice = ExeCutors.newsinglethreadexecutor ();
2. Add a task to a thread to perform when a task is added to the thread pool, the thread pool creates one for each task, which is executed automatically at a later point in time.
Third, close the execution service objectExecutorservice.shutdown ();
Iv. Comprehensive ExamplesPackage concurrent;
import Java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by IntelliJ idea.
*
* @author leizhimin 2008-11-25 14:28:59
*/
public class Testcachedthreadpool {
Public static void main (string[] args) {
// Executorservice Executorservice = Executors.newcachedthreadpool ();
Executorservice Executorservice = Executors.newfixedthreadpool (5); //Executorservice Executorservice = Executors.newsinglethreadexecutor ();
for (int i = 0; I < 5; i++) {
Executorservice.execute (New Testrunnable ());
System.out.println ("************* a" + i +" *************");
}
Executorservice.shutdown ();
}
}
Class TestrunnableImplements Runnable {
Publicvoid Run () {
System.out.println (Thread.CurrentThread (). GetName () +"The thread was called. ");
while (True) {
try {
Thread.Sleep (5000);
System.out.println (Thread.CurrentThread (). GetName ());
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}Running result: ************* A0 *************
A1 *************
The pool-1-thread-2 thread was called.
A2 *************
The pool-1-thread-3 thread was called.
The pool-1-thread-1 thread was called.
A3 *************
A4 *************
The pool-1-thread-4 thread was called.
The pool-1-thread-5 thread was called.
Pool-1-thread-2
Pool-1-thread-1
Pool-1-thread-3
Pool-1-thread-5
Pool-1-thread-4
Pool-1-thread-2
Pool-1-thread-1
Pool-1-thread-3
Pool-1-thread-5
Pool-1-thread-4
...... V. Get the return value of the execution of a task after Java5, the task is divided into two classes: one is the class that implements the Runnable interface, and the other is the class that implements the callable interface. Both can be executed by Executorservice, but the runnable task does not return a value, and the callable task has a return value. and callable's call () method can only be used by Executorservice's
Submit(callable<T> Task) method to execute and return a <T> future <t>, which represents the future of the task waiting to be completed.
Callable<v>
a task that returns the result and may throw an exception. The implementing person defines a method called call without any parameters . The callable interface is similar in
Runnable
that both are designed for classes whose instances might be executed by another thread. However , Runnable does not return a result and cannot throw a checked exception.
Executors
class contains some practical methods for converting from other ordinary forms to callable classes. the call () method in callable is similar to the runnable run () method, where the former has a return value and the latter does not. when a callable object is passed to the Executorservice's Submit method, the call method executes automatically on a thread and returns the execution result to the future object. Similarly, the Runnable object is passed to the Executorservice's Submit method, the Run method is executed automatically on a thread, and the execution result is returned to the future object, but the Get method is called on the future object. will return NULL. Unfortunately, in the Java API documentation, this piece of introduction is very confusing, it is estimated that the translator is not clear about it. Or a comment that is not in place. Let's look at an example:Import java.util.ArrayList;
Import java.util.List;
Import java.util.concurrent.*;
/**
* Callable Interface Test
*
* @author leizhimin 2008-11-26 9:20:13
*/
PublicClass Callabledemo {
PublicStaticvoid Main (string[] args) {
Executorservice Executorservice = Executors.newcachedthreadpool ();
List<future<string>> resultlist =New Arraylist<future<string>> ();
Create 10 of tasks and execute
for (int i = 0; I < 10; i++) {
Use Executorservice to perform callable types of tasks and save the results in future variables
future<string> future = Executorservice.submit (New Taskwithresult (i));
To store task execution results in a list
Resultlist.add (future);
}
Traverse the results of a task
for (future<string> fs:resultlist) {
try {
System.out.println (Fs.get ());Print the results of each thread (Task) execution
}catch (Interruptedexception e) {
E.printstacktrace ();
}catch (Executionexception e) {
E.printstacktrace ();
}finally {
Starts a sequential shutdown, performs a previously submitted task, but does not accept new tasks. If it is already closed, the call has no other effect.
Executorservice.shutdown ();
}
}
}
}
Class TaskwithresultImplements Callable<string> {
Privateint id;
Public Taskwithresult (int id) {
This.id = ID;
}
/**
* The specific process of the task, once the task is passed to Executorservice's Submit method, the method is automatically executed on a thread.
*
* @return
* @throws Exception
*/
Public String Call ()Throws Exception {
System.out.println ( "call () method is automatically called, Work!!! "+ thread.currentthread (). GetName ());
//a simulated time-consuming operation
for (int i = 999999; i > 0; i--);
return "call () method is automatically called, the result of the task is:" + ID + " "+ thread.currentthread (). GetName ();
}
} Operation Result: Call () method is automatically called, Work!!! Pool-1-thread-1
Call () method is automatically called, Work!!! Pool-1-thread-3
Call () method is automatically called, Work!!! Pool-1-thread-4
Call () method is automatically called, Work!!! Pool-1-thread-6
Call () method is automatically called, Work!!! Pool-1-thread-2
Call () method is automatically called, Work!!! Pool-1-thread-5
The call () method is called automatically, and the result of the task is: 0 pool-1-thread-1
The call () method is called automatically, and the result of the task is: 1 pool-1-thread-2
Call () method is automatically called, Work!!! Pool-1-thread-2
Call () method is automatically called, Work!!! Pool-1-thread-6
Call () method is automatically called, Work!!! Pool-1-thread-4
The call () method is called automatically, and the result of the task is: 2 pool-1-thread-3
Call () method is automatically called, Work!!! Pool-1-thread-3
The call () method is called automatically, and the result of the task is: 3 pool-1-thread-4
The call () method is called automatically, and the result of the task is: 4 pool-1-thread-5
The call () method is called automatically, and the result of the task is: 5 pool-1-thread-6
The call () method is called automatically, and the result of the task is: 6 pool-1-thread-2
The call () method is called automatically, and the result of the task is: 7 pool-1-thread-6
The call () method is called automatically, and the result of the task is: 8 pool-1-thread-4
The call () method is called automatically, and the result of the task is: 9 pool-1-thread-3
Process finished with exit code 0
Java5 Concurrent Learning