1. 程式人生 > >Java執行緒池用法總結

Java執行緒池用法總結

1、執行緒池

1) 建立測試執行緒

private static class MyThread extends Thread{
	@Override
	public void run() {
		super.run();
		System.out.println(Thread.currentThread().getName()+"正在執行。。。");
	}
}
2) 建立執行緒池物件
//建立單執行緒執行緒池,執行緒序列執行
ExecutorService pool = Executors.newSingleThreadExecutor();
//建立固定大小的執行緒池
ExecutorService pool = Executors.newFixedThreadPool(2);
//執行緒池大小彈性變化
ExecutorService pool = Executors.newCachedThreadPool();
3) 執行執行緒
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
Thread t5 = new MyThread();
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
4) 關閉執行緒池
pool.shutdown();
5) 定時、週期性執行的執行緒池
//定時、週期性執行任務,跟Timer、TimerTask類似
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleAtFixedRate(new Runnable() {
	@Override
	public void run() {
		//long, measure elapsed time
		System.out.println(System.nanoTime());
	}
}, 1000, 2000, TimeUnit.MILLISECONDS);