Java 5 Concurrent learning

Source: Internet
Author: User

After Java 5, the concurrent thread has undergone a fundamental change. The most important thing is a bunch of new APIs for starting, scheduling, and managing threads. After Java 5, it is better to use Executor to start a Thread than to use Thread start. In the new features, the thread startup, execution, and shutdown processes can be easily controlled, and the features of the thread pool can be easily used.
 
1. Create a task
 
A task is a class that implements the Runnable interface.
The actual run method can be used during creation.
 
Ii. Execute the task
 
The java. util. concurrent. ExecutorService interface object is used to execute tasks. This interface object is created through the static method of java. util. concurrent. Executors in the tool class.
 
Executors the factory and practical methods for the Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package.
 
ExecutorService provides a way to manage termination and generate a Future for tracking the execution of one or more asynchronous tasks. You can disable ExecutorService, which causes it to stop accepting new tasks. After it is closed, the execution program will be terminated. At this time, no task is being executed, No task is waiting for execution, and new tasks cannot be submitted.
ExecutorService.exe cute (new TestRunnable ());
 
1. Create ExecutorService
The tool class java. util. concurrent. Executors is used to create a static method.
Executors the factory and practical methods for the Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package.
 
For example, to create an ExecutorService instance, 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 the task to the thread for execution.
When a task is added to the thread pool, the thread pool creates a thread for each task, which is automatically executed at a later time.
 
3. Close the execution service object
ExecutorService. shutdown ();
 
Iv. Integrated instances
 
Package concurrent;

Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;

/**
* Created by IntelliJ IDEA.
*
* @ Author leizhimin 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.exe cute (new TestRunnable ());
System. out. println ("************** a" + I + "*************");
}
ExecutorService. shutdown ();
}
}

Class TestRunnable implements Runnable {
Public void run (){
The System. out. println (Thread. currentThread (). getName () + "Thread is called. ");
While (true ){
Try {
Thread. sleep (5000 );
System. out. println (Thread. currentThread (). getName ());
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
}
 
Running result:
* ***********A0 *************
*************
The pool-1-thread-2 thread is called.
* ************** A2 *************
The pool-1-thread-3 thread is called.
The pool-1-thread-1 thread is called.
* ***********A3 *************
*************
The pool-1-thread-4 thread is called.
The pool-1-thread-5 thread is 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
......
 
 
5. Obtain the returned values of task execution
After Java 5, there are two types of tasks: 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 has no return value, while the Callable task has a return value. Besides, the call () method of Callable can only be executed through the submit (Callable <T> task) method of ExecutorService, and a <T> Future <T> is returned, is the Future of the task.
 
Public interface Callable <V>

A task that returns results and may throw exceptions. The implementer defines a method called call without any parameters.
The Callable interface is similar to Runnable, both of which are designed for classes whose instances may be executed by another thread. However, Runnable does not return results and cannot throw a checked exception.
The Executors class contains some practical methods for converting from other common forms to Callable classes.
 
 
The call () method in Callable is similar to the Runnable run () method, that is, the former has a return value, and the latter does not.
 
When a Callable object is passed to the submit method of ExecutorService, the call method is automatically executed on a thread and the execution result Future object is returned.
 
Similarly, if the Runnable object is passed to the submit method of ExecutorService, the run method is automatically executed on a thread and the execution result Future object is returned, however, if the get method is called on the Future object, null is returned.
 
Unfortunately, in the Java API documentation, this section is very confusing. It is probably because the translators have not figured it out yet. Or the comment is not in place. The following is an example:
 
Import java. util. ArrayList;
Import java. util. List;
Import java. util. concurrent .*;

/**
* Callable Interface Test
*
* @ Author leizhimin 9:20:13
*/
Public class CallableDemo {
Public static void main (String [] args ){
ExecutorService executorService = Executors. newCachedThreadPool ();
List <Future <String> resultList = new ArrayList <Future <String> ();

// Create and execute 10 tasks
For (int I = 0; I <10; I ++ ){
// ExecutorService is used to execute Callable tasks and save the results in the future variable.
Future <String> future = executorService. submit (new TaskWithResult (I ));
// Store the task execution result to the List
ResultList. add (future );
}

// Traverse the task result
For (Future <String> fs: resultList ){
Try {
System. out. println (fs. get (); // print the execution results of each thread (task)
} Catch (InterruptedException e ){
E. printStackTrace ();
} Catch (ExecutionException e ){
E. printStackTrace ();
} Finally {
// Start and close the task in sequence, and execute the previously submitted task, but do not accept the new task. If it is disabled, the call has no other effect.
ExecutorService. shutdown ();
}
}
}
}


Class TaskWithResult implements Callable <String> {
Private int id;

Public TaskWithResult (int id ){
This. id = id;
}

/**
* The specific process of a task. Once the task is passed to the submit method of ExecutorService, the method is automatically executed on a thread.
*
* @ Return
* @ Throws Exception
*/
Public String call () throws Exception {
The System. out. println ("call () method is automatically called. Work !!! "+ Thread. currentThread (). getName ());
// Simulate a time-consuming operation
For (int I = 999999; I> 0; I --);
The return "call () method is automatically called. The result of the task is:" + id + "" + Thread. currentThread (). getName ();
}
}
 
Running result:
The call () method is automatically called. Work !!! Pool-1-thread-1
The call () method is automatically called. Work !!! Pool-1-thread-3
The call () method is automatically called. Work !!! Pool-1-thread-4
The call () method is automatically called. Work !!! Pool-1-thread-6
The call () method is automatically called. Work !!! Pool-1-thread-2
The call () method is automatically called. Work !!! Pool-1-thread-5
The call () method is automatically called. The result of the task is: 0 pool-1-thread-1.
The call () method is automatically called. The result of the task is: 1 pool-1-thread-2.
The call () method is automatically called. Work !!! Pool-1-thread-2
The call () method is automatically called. Work !!! Pool-1-thread-6
The call () method is automatically called. Work !!! Pool-1-thread-4
The call () method is automatically called. The result of the task is 2 pool-1-thread-3.
The call () method is automatically called. Work !!! Pool-1-thread-3
The call () method is automatically called, and the result of the task is: 3 pool-1-thread-4
The call () method is automatically called. The result of the task is 4 pool-1-thread-5.
The call () method is automatically called. The result of the task is 5 pool-1-thread-6.
The call () method is automatically called. The result of the task is 6 pool-1-thread-2.
The call () method is automatically called. The result of the task is 7 pool-1-thread-6.
The call () method is automatically called. The task result is: 8 pool-1-thread-4.
The call () method is automatically called. The result of the task is: 9 pool-1-thread-3.

Process finished with exit code 0

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.