import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 使用一个线程池时,要考虑阻塞队列的容量是不充足的。如何解决,适当的时候将任务放到队列中去
* 要消耗掉任务
* 一个线程用于想阻塞任务队列中存放数据
* 一个线程池用于处理任务队列中的任务
* @author root
*
*/
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
final ArrayBlockingQueue<Runnable> abk = new ArrayBlockingQueue<Runnable>(2);
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
2,
5,
30,
TimeUnit.SECONDS,
abk,new ThreadPoolExecutor.DiscardOldestPolicy());
new Thread(){
public void run(){
for(int i = 1; i < 10; ++i){
while(abk.size() == 2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
abk.put(new WorkThread(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
while(true){
if(abk.size() > 0){
try {
tpe.submit(abk.take());//用take()方法,不要使用poll方法,两者有区别的,take()方法为阻塞方法
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
工作线程类:
public class WorkThread implements Runnable{
public int taskf = 0;
public WorkThread(int taskf){
this.taskf = taskf;
}
public void run() {
new ThreadTask(taskf).execute();
}
}
具体任务类:
public class ThreadTask {
int task = 0;
public ThreadTask(int task){
this.task = task;
}
public void execute(){
System.out.println(Thread.currentThread().getName()+"----------"+task);
}
}