線程阻塞,java線程阻塞
研究ThreadPoolExecutor.excute()源碼會發現,它調用了BlockingQueue.offer()來實現多餘任務的入隊。BlockingQueue有兩個方法:BlockingQueue.offer()和BlockingQueue.put(),前者在隊列滿時不阻塞,直接失敗,後者在隊列滿時阻塞。那麼,問題就很簡單了,繼承某個BlockingQueue,然後將offer()重寫,改成調用put()就搞定了!最短的代碼量,也能起到很好的效果哦!
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{ /** * 建立一個堵塞隊列 * * @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 = -9028058603126367678L; @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.execute(new myThread()); service.execute(new myThread()); service.execute(new myThread()); service.execute(new myThread()); service.execute(new myThread()); service.shutdown(); }}class myThread extends Thread{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"正在運行。。。。。。"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }