[Java] creating a blocking Thread Pool

Source: Internet
Author: User

It turns out that tiger already comes with this thread pool, that is, when the number of tasks exceeds the limit, the thread that can block the tasks to be placed is mainly used for JMS message listening.

Start:
In threadpoolexcecutor, new arrayblockingqueue (max_task) is input. if the task is exceeded, the error "rejectedexecutionexception" is returned.

Later, you don't need to execute the method to add a task. Instead, you can directly getqueue (). Add (task) and use its blocking feature. However, blocking is easy to use, but the task is not processed. After reading the queue, I was dizzy. It was originally in it and the task pool did not process it. The task pool is required.

Finally, we reload a blockedthreadpoolexecutor:

  Private Reentrantlock pauselock =   New Reentrantlock ();
 
Private Condition unpaused = Pauselock. newcondition ();
@ Override
 
Public   Void Execute (runnable command) {
Pauselock. Lock ();
Try   {
While(Getpoolsize ()=Getmaximumpoolsize ()&&Getqueue (). remainingcapacity ()=0)
Unpaused. Await ();
Super. Execute (command );//Put it out of the lock, there will be leakage in the stress test!
}
  Catch (Interruptedexception E) {
Log. Warn (
This, E );
}
  Finally   {
Pauselock. Unlock ();
}

}

@ Override
 
Protected   Void Afterexecute (runnable R, throwable T) {
Super . Afterexecute (R, t );
Try {
Pauselock. Lock ();
Unpaused. Signal ();
}
Finally {
Pauselock. Unlock ();
}

}

MultithreadingProgramIt is easy to make mistakes. If you have completed the writing, you should try your best to use stress testing. Otherwise, there will be a lot of problems ~~~

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.