我想实现一个这样的效果:
线程里面,各自带一个阻塞队列,拿到元素则处理。
然后把几个线程放进线程池里。想利用线程池控制最大可同时执行的线程数,线程池内的线程在不超过同时执行数限制的情况下,各自抢占式执行消费自己的队列,有什么办法可以实现吗?
试过了
newFixedThreadPool,
newWorkStealingPool,
newCachedThreadPool
都不能满足,因为提交的线程都有while(true),永远不会执行完,而被自身的队列阻塞时,线程池似乎也不会腾出资源执行别的队列非空线程,不知有没什么办法可以实现,求教~~
尝试的实例代码如下:
public static void main(String[] args) throws InterruptedException {
Thread001 t1 = new Thread001();
Thread001 t2 = new Thread001();
Thread001 t3 = new Thread001();
Thread001 t4 = new Thread001();
ExecutorService obj = Executors.newFixedThreadPool(3);
obj.execute(t1);
obj.execute(t2);
obj.execute(t3);
obj.execute(t4);
t1.queue.add("t1");
t2.queue.add("t2");
t3.queue.add("t3");
t4.queue.add("t4");
Thread.sleep(2000);
t1.queue.add("t5");
Thread.sleep(10000);
}
----------------------------------------------------------------
public class Thread001 implements Runnable{
public LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
@Override
public void run() {
while(true){
String s;
try {
s = queue.take();
System.out.println("T1:"+s);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
运行结果:
T1:t1
T1:t3
T1:t2
T1:t5