Recent work requires statistics on some complex reports. To improve efficiency, we want to use multiple threads for implementation. However, we need to summarize the results after all threads complete the statistical tasks. So I am thinking about whether there is any solution. The reason is "Series 1" is that I want to record my thinking process.
1. First, design an Executer to execute and summarize the tasks:
Java code
Public class Executer {
// Calculate the number of distributed tasks (condition predicates)
Public static int THREAD_COUNT = 0;
// Thread Pool
Private Executor pool = null;
Public Executer (){
This (1 );
}
Public Executer (int threadPoolSize ){
Pool = Executors. newFixedThreadPool (threadPoolSize );
}
/**
* Task Distribution
* @ Param job
*/
Public void fork (Job job ){
// Dispatch the task to the thread pool for execution
Pool.exe cute (job );
THREAD_COUNT ++;
}
/**
* Statistical task results
*/
Public void join (){
While (THREAD_COUNT> 0 ){
System. out. println ("threadCount:" + THREAD_COUNT );
Try {
Wait (); // It is suspended if not all tasks are completed.
} Catch (Exception e) {}// an Exception is always thrown here. I don't know why, okay! Ignore it first
}
}
}
2. Write an abstract Job class to execute specific tasks.
Java code
Public abstract class Job implements Runnable {
@ Override
Public void run (){
This.exe cute (); // executes the specific task of the subclass.
Executer. THREAD_COUNT --;
Try {
Yyall (); // exceptions are always thrown here. I don't know why, okay! Ignore it first
} Catch (Exception e ){}
}
/**
* Business processing functions
*/
Public abstract void execute ();
}
3. test. A specific task is implemented first.
Java code
Public class MyJob extends Job {
@ Override
Public void execute (){
// The simulation service takes 1 second.
Try {Thread. sleep (1000);} catch (InterruptedException e ){}
System. out. println ("running thread id =" + Thread. currentThread (). getId ());
}
}
4. Test.
Java code
Public class Test {
Public static void main (String [] args ){
// Initialize the task pool
Executer exe = new Executer (5 );
// Initialize the task
Long time = System. currentTimeMillis ();
For (int I = 0; I <10; I ++ ){
MyJob job = new MyJob ();
Exe. fork (job); // dispatch a task
}
// Summarize the task results
Exe. join ();
System. out. println ("time:" + (System. currentTimeMillis ()-time ));
}
}
5. Let's take a look at the results.
Java code
ThreadCount: 10
... (Meaning there are more than N)
ThreadCount: 10
Running thread id = 8
Running thread id = 9
Running thread id = 11
Running thread id = 10
Running thread id = 12
ThreadCount: 5
... (Meaning there are more than N)
ThreadCount: 5
Running thread id = 9
Running thread id = 10
Running thread id = 12
Running thread id = 8
Running thread id = 11
ThreadCount: 3
Time: 2032
Haha, it seems yes. The processing time of the final summary task is 2032 ms, which seems to be faster than the sequential execution of a single task. But there are several problems:
1) if the catch super Exception is not found, the following Exception will be thrown:
Java code
Java. lang. IllegalMonitorStateException
At java. lang. Object. wait (Native Method)
At java. lang. Object. wait (Object. java: 485)
At com. one. Executer. join (Executer. java: 38)
At com. test. Test. main (Test. java: 21)
2) Why will N multiple identical threadCount be printed?
So I communicated with my colleague (Hedong). He said that wait should be placed in synchronized. Well, give it a try and improve Executer and Job.
Java code
Public class Executer {
// Calculate the number of distributed tasks (condition predicates)
Public static int THREAD_COUNT = 0;
// Condition queue lock
Public static final Object LOCK = new Object ();
// Thread Pool
Private Executor pool = null;
Public Executer (){
This (1 );
}
Public Executer (int threadPoolSize ){
Pool = Executors. newFixedThreadPool (threadPoolSize );
}
/**
* Task Distribution
* @ Param job
*/
Public void fork (Job job ){
// Dispatch the task to the thread pool for execution
Pool.exe cute (job );
// Increase the number of threads
Synchronized (LOCK ){
THREAD_COUNT ++;
}
}
/**
* Statistical task results
*/
Public void join (){
Synchronized (LOCK ){
While (THREAD_COUNT> 0 ){
System. out. println ("threadCount:" + THREAD_COUNT );
Try {
LOCK. wait (); // if not all tasks are completed, the task is suspended.
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
}
}
Java code
Public abstract class Job implements Runnable {
@ Override
Public void run (){
This.exe cute (); // executes the specific task of the subclass.
Synchronized (Executer. 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 --;
Executer. LOCK. policyall ();
}
}
/**
* Business processing functions
*/
Public abstract void execute ();
}
6. test:
Java code
ThreadCount: 10
Running thread id = 8
Running thread id = 11
Running thread id = 9
ThreadCount: 7
Running thread id = 10
ThreadCount: 6
Running thread id = 12
ThreadCount: 5
Running thread id = 11
Running thread id = 12
Running thread id = 10
ThreadCount: 2
Running thread id = 9
Running thread id = 8
ThreadCount: 1
Time: 2016