http://blog.csdn.net/cutesource/article/details/6061229
package thread;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 这个例子演示的效果为:
* 在一个线程池threadPool里面,同时只能有一个线程运行,
* 如果threadPool里面又线程正在运行,当向threadPool中sumit新任务的时候,
* 就会被 RejectedExecutionHandler 截获处理
* @author zhoufeng
*/
public class Thread06 {
private static BlockingQueue<Runnable> workQueue =
new SynchronousQueue<Runnable>(); //如果使用该队列,同时只能有一个任务存在。否则就抛异常
// new LinkedBlockingQueue<Runnable>(1); //如果用该队列,就能够同时存在多个任务
private static final ExecutorService threadPool =
new ThreadPoolExecutor(1, 1, 0 ,
TimeUnit.MILLISECONDS , workQueue, new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("上一个任务还没结束,添加任务失败!");
}
}) ;
public static void addTask(){
threadPool.submit(new Runnable() {
public void run() {
try {
System.out.println("start task ...");
TimeUnit.SECONDS.sleep(5);
System.out.println("end task...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}) ;
}
public static void main(String[] args) throws Exception{
//当上一个任务没有执行完毕,就添加下一个任务,会抛出异常,而不是进入等待
addTask();
// TimeUnit.SECONDS.sleep(5);
addTask();
// TimeUnit.SECONDS.sleep(5);
addTask();
}
}