你的位置:首页 > Java教程

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