啓動三個線程A,B,C,打印10次 按照ABC的順序輸出

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ABC5 {

	private int cond = 1;// 通過cond來確定A B C的輸出
	private Lock lock = new ReentrantLock();// 通過JDK5中的鎖來保證線程的訪問的互斥
	private Condition condition = lock.newCondition();// 線程協作

	public static void main(String[] args) {
		ABC5 abc = new ABC5();// 內部類線程執行方式jdk1.5
		ThreadA ta = abc.new ThreadA();// 聲明3個runnable類
		ThreadB tb = abc.new ThreadB();
		ThreadC tc = abc.new ThreadC();
		ExecutorService executor = Executors.newFixedThreadPool(3);// 通過線程池執行
		for (int i = 0; i < 10; i++) {
			executor.execute(ta);
			executor.execute(tb);
			executor.execute(tc);
		}
		executor.shutdown();// 關閉線程池

	}

	class ThreadA implements Runnable {

		public void run() {
			lock.lock();
			try {
				while (true) {
					if (cond % 3 == 1) {
						System.out.print(cond+":A");
						cond++;
						condition.signalAll();
						break;
					} else {
						try {
							condition.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			} finally {
				lock.unlock();
			}
		}

	}

	class ThreadB implements Runnable {
		public void run() {
			lock.lock();
			try {
				while (true) {
					if (cond % 3 == 2) {
						System.out.print(cond+":B");
						cond++;
						condition.signalAll();
						break;
					} else {
						try {
							condition.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			} finally {
				lock.unlock();
			}
		}

	}

	class ThreadC implements Runnable {
		public void run() {
			lock.lock();
			try {
				while (true) {
					if (cond % 3 == 0) {
						System.out.println(cond+":C");
						cond++;
						condition.signalAll();
						break;
					} else {
						try {
							condition.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			} finally {
				lock.unlock();
			}
		}

	}

}


 

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