Thread blocking, java thread Blocking

Source: Internet
Author: User

Thread blocking, java thread Blocking

Studying the ThreadPoolExecutor. excute () source code, we will find that it calls BlockingQueue. offer () to queue redundant tasks. BlockingQueue has two methods: BlockingQueue. offer () and BlockingQueue. put (). The former does not block when the queue is full, and directly fails. The latter blocks when the queue is full. Then, the problem is simple. inherit a BlockingQueue and rewrite the offer () into put! The shortest amount of code can also have good results!

Import java. util. concurrent. executorService; import java. util. concurrent. linkedBlockingQueue; import java. util. concurrent. threadPoolExecutor; import java. util. concurrent. timeUnit; public class ExecutorsEx extends Thread {/*** create a blocking queue ** @ param threadSize * @ return */public static ExecutorService newFixedThreadPool (int threadSize) {return new ThreadPoolExecutor (threadSize, threadSize, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> (1) {private static final long serialVersionUID =-9028058603126379678l; @ Override public boolean offer (Runnable e) {try {put (e ); return true;} catch (InterruptedException ie) {Thread. currentThread (). interrupt () ;}return false ;}});} public static void main (String [] args) {ExecutorService service = ExecutorsEx. newFixedThreadPool (2); service. e Xecute (new myThread (); service.exe cute (new myThread ()); service.exe cute (new myThread (); service. shutdown () ;}} class myThread extends Thread {@ Override public void run () {System. out. println (Thread. currentThread (). getName () + "running ...... "); Try {Thread. sleep (2000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

 

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.