Optimize the lock. The previous lock is implemented using a static Object. This requires a problem. If I create multiple Executer s, all jobs will hold a lock, it affects both performance and deadlock. Therefore, each Executer holds a lock.
Executer code:
Java code
Public class Executer {
// Calculate the number of distributed tasks (condition predicates)
Public static int THREAD_COUNT = 0;
// Store the execution result of the task
Private List <Future <Object> futres = new ArrayList <Future <Object> ();
// Condition queue lock
Public final Object lock = new Object ();
// Thread Pool
Private ExecutorService pool = null;
Public Executer (){
This (1 );
}
Public Executer (int threadPoolSize ){
Pool = Executors. newFixedThreadPool (threadPoolSize );
}
/**
* Task Distribution
* @ Param job
*/
Public void fork (Job job ){
// Set the synchronization lock
Job. setLock (lock );
// Dispatch the task to the thread pool for execution
Futres. add (pool. submit (job ));
// Increase the number of threads
Synchronized (lock ){
THREAD_COUNT ++;
}
}
/**
* Statistical task results
*/
Public List <Object> join (){
Synchronized (lock ){
While (THREAD_COUNT> 0) {// check the number of threads. If it is 0, all tasks are processed completely.
System. out. println ("threadCount:" + THREAD_COUNT );
Try {
Lock. wait (); // if the task is not completed, it is suspended. Notification of tasks awaiting completion
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
List <Object> list = new ArrayList <Object> ();
// Retrieve the processing results of each task and return the summary
For (Future <Object> future: futres ){
Try {
Object result = future. get (); // get
List. add (result );
} Catch (Exception e ){
E. printStackTrace ();
}
}
Return list;
}
}
Job class:
Java code
Public abstract class Job implements Callable <Object> {
// Lock
Private Object lock = null;
Void setLock (Object lock ){
This. lock = lock;
}
@ Override
Public Object call () throws Exception {
Object result = this.exe cute (); // executes the specific task of the subclass.
Synchronized (lock ){
// After the service is processed, the task ends and the number of threads is decreased. At the same time, the main thread is awakened.
Executer. THREAD_COUNT --;
Lock. policyall ();
}
Return result;
}
/**
* Business processing functions
*/
Public abstract Object execute ();
}
Test results:
Java code
ThreadCount: 10
Running thread id = 8
Running thread id = 10
Running thread id = 9
Running thread id = 12
Running thread id = 11
ThreadCount: 8
ThreadCount: 7
ThreadCount: 6
ThreadCount: 5
Running thread id = 12
Running thread id = 8
Running thread id = 11
ThreadCount: 2
Running thread id = 10
ThreadCount: 1
Running thread id = 9
ResultSize: 10
Time: 2001