Simple concurrent applications
A new package is added to the JDK 1.5 API.
Java. util. Concurrent is a commonly used Utility Class in concurrent programming.
Java. util. Concurrent. Locks provides a framework interface and class for locking and waiting conditions, which is different from built-in synchronization and monitoring.
Class Diagram under this package
Common classes:
Executors provides a method to establish a thread pool or thread factory.
Executorservice provides a way to manage termination and generate a future for tracking the execution of one or more asynchronous tasks.
Executor can be simply understood as the executor of a thread.
Future indicates the result of asynchronous calculation. The execution result can be obtained by checking the status of the executed thread.
FutureTask provides the basic implementation of Future. You can use FutureTask to wrap Callable or Runnable objects. Therefore, you can submit FutureTask to Executor for execution.
Interface to be implemented by the Callable thread
Semaphore is a counting Semaphore, which is usually used to limit the number of threads that can access certain resources (physical or logical.
For more details about the application of classes and methods, refer to the API
The following is a simple example:
(Limit the number of concurrent threads)
- Public
Static
Void
Main (String [] args ){
// Thread Pool
- ExecutorService exec = Executors. newCachedThreadPool ();
// Only five threads can simultaneously access
Final
Semaphore semp =
New
Semaphore (
5
);
// Simulate access from 20 clients
For
(
Int
Index =
0
; Index <
20
; Index ++ ){
Final
Int
NO = index;
- Runnable run =
New
Runnable (){
Public
Void
Run (){
Try
{
// Obtain the license
- Semp. acquire ();
- System. out. println (
"Thread :"
+ NO );
- Thread. sleep ((
Long
) (Math. random ()*
1000
));
// Release after access
- SEMP. Release ();
- }
Catch
(Interruptedexception e ){
- }
- }
- };
- Exec.exe cute (run );
- }
// Exit the thread pool
- Exec. shutdown ();
- }
Simple thread pool management:
- Import
Java. util. concurrent. Callable;
- Import
Java. util. concurrent. ExecutionException;
- Import
Java. util. concurrent. ExecutorService;
- Import
Java. util. concurrent. Executors;
- Import
Java. util. concurrent. Future;
- Import
Java. util. concurrent. FutureTask;
- Import
Java. util. concurrent. Semaphore;
- /**
- * Management class of Thread Pool
- * Obtain such instances through static methods
- */
- Public
Class
ThreadPoolManager <T> {
Private
ExecutorService service =
Null
;
Private
Final
Semaphore semp;
Private
Int
MaxNum =
3
;
Private
Static
ThreadPoolManager me =
Null
;
Public
Static
ThreadPoolManager getInstance (){
If
(Me =
Null
){
- Me =
New
ThreadPoolManager ();
- }
Return
Me;
- }
Public
Static
ThreadPoolManager getInstance (
Int
MaxNum ){
If
(Me =
Null
){
- Me =
New
Threadpoolmanager (maxnum );
- }
Return
Me;
- }
Private
Threadpoolmanager (){
- Service = executors. newcachedthreadpool ();
- SEMP =
New
Semaphore (maxnum );
- }
Private
Threadpoolmanager (
Int
Maxnum ){
This
. Maxnum = maxnum;
- Service = executors. newcachedthreadpool ();
- SEMP =
New
Semaphore (maxnum );
- }
/**
- * Executes a thread task and returns the result.
- * If the number of thread pools is all occupied, the thread is blocked.
- * The implementation method of the input parameter class for thread running.
- * @ Param task implement the java. util. concurrent. Callable Interface Class
- * @ Return returns the result of thread running.
- * @ Throws InterruptedException
- * @ Throws ExecutionException
- */
Public
T runTask (Callable <T> task)
Throws
InterruptedException, ExecutionException {
- Semp. acquire ();
// Use signal flag. If the number is exceeded, thread blocking will occur.
- Future <t> F = service. Submit (task );
// Load the thread task and execute
- SEMP. Release ();
// Signal release
Return
F. Get ();
// Return the processing result of the thread. If the processing is not completed, the thread is blocked until the returned result is returned.
- }
/**
- * @ Return the number of available return threads
- */
Public
Synchronized
Int
Getavailablenum (){
Return
This
. SEMP. availablepermits ();
- }
/**
- * Close the thread pool.
- */
Public
Final
Void
Close (){
- Service. shutdown ();
- }
- }