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 ();}}}