码迷,mamicode.com
首页 > 编程语言 > 详细

线程阻塞

时间:2015-12-23 12:19:51      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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

 

线程阻塞

标签:

原文地址:http://www.cnblogs.com/zc902603/p/5069207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!