一個使用執行緒計數器的例子

longerandlonger發表於2012-12-10

需求描述:主執行緒掛起,作為守護執行緒。執行緒池裡,每當一個執行緒結束後,計數器減一。當執行緒池裡所有執行緒都結束後,通知主執行緒,使得主執行緒可以繼續。


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestCountDownLatch {
	public static void main(String[] args) {
		final int num = 1000;
		
		//執行緒通訊計數器
		CountDownLatch end = new CountDownLatch(num);
		
		//初始化任務執行緒池
		ExecutorService exe = Executors.newFixedThreadPool(num);
		
		for (int n=0; n<num; ++n) {
			exe.execute(new MyRunable(end, n));
		}
		
		try {
			end.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


class MyRunable implements Runnable {
	
	private CountDownLatch end;
	private int id;
	
	public MyRunable(CountDownLatch end, int id) {
		this.end = end;
		this.id = id;
	}
	
	@Override
	public void run() {
		System.out.println();
		System.out.println(String.format("Begin:id=%s;end=%s", id, end.getCount()));
		end.countDown();
		System.out.println(String.format("End:id=%s;end=%s", id, end.getCount()));
		System.out.println();
	}
}


相關文章