用CountDownLatch模擬學生入校操作

想象場景

學校開門了學生才能入校,當全部10名學生都入校後打印入校完畢,程序退出

package study;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Test {
	public static class myThread extends Thread {
		int sleepSeconds;
		CountDownLatch doorOpen; // 控制開門
		CountDownLatch doorClose; // 控制鎖門
		public myThread(String name,int seconds,CountDownLatch doorOpen,CountDownLatch doorClose) {
			this.setName(name);
			this.sleepSeconds = seconds;
			this.doorOpen = doorOpen;
			this.doorClose = doorClose;
		}
		@Override
		public void run() {
			System.out.println(this.getName() + "準備入校");
			try {
				doorOpen.await();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			long startTime = System.currentTimeMillis();
			System.out.println(this.getName() + "開始入校");
			try {
				TimeUnit.SECONDS.sleep(sleepSeconds);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				long endTime = System.currentTimeMillis();
				System.out.println(this.getName() + "入校完畢,耗時:" + String.valueOf(endTime - startTime));
				doorClose.countDown();
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch doorOpen = new CountDownLatch(1);
		CountDownLatch doorClose = new CountDownLatch(10);
		long start = System.currentTimeMillis();
		System.out.println("------學校準備開門了------");
		TimeUnit.SECONDS.sleep(5);
		doorOpen.countDown(); // 這裏就是學校開門操作
		for(int index = 0; index < 10; index++) {
			new myThread("學生" + String.valueOf(index + 1), 1, doorOpen, doorClose).start();
		}
		doorClose.await();
		long end = System.currentTimeMillis();
		System.out.println("所有學生入校完畢,耗時:" + String.valueOf(end - start));
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章