使用线程池例子





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

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值