Java多線程與併發應用-(11)-用Lock+Condition實現1,2,3 三個模塊按順序執行。

package com.lipeng;

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

/**
 * 實現1,2,3模塊按順序執行
 * 
 * @author LP
 * 
 */
public class LockAndConditionDemo {
	private Lock lock = new ReentrantLock();
	private int taskNo = 1;// 當前該執行的模塊,默認爲1.
	private Condition c1 = lock.newCondition();
	private Condition c2 = lock.newCondition();
	private Condition c3 = lock.newCondition();

	public void task1() {
		try {
			lock.lock();
			while (taskNo != 1) {
				try {
					c1.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("task1執行");
			taskNo = 2;
			c2.signal();
		} finally {
			lock.unlock();
		}
	}

	public void task2() {
		try {
			lock.lock();
			while (taskNo != 2) {
				try {
					c2.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("task2執行22222222222222");
			taskNo = 3;
			c3.signal();
		} finally {
			lock.unlock();
		}
	}

	public void task3() {
		try {
			lock.lock();
			while (taskNo != 3) {
				try {
					c3.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("task3執行333333333333333333333333333333333");
			taskNo = 1;
			c1.signal();
		} finally {
			lock.unlock();
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final LockAndConditionDemo lockAndConditionDemo = new LockAndConditionDemo();
		Runnable run1 = new Runnable() {

			@Override
			public void run() {
				lockAndConditionDemo.task1();
			}
		};
		Runnable run2 = new Runnable() {

			@Override
			public void run() {
				lockAndConditionDemo.task2();
			}
		};
		Runnable run3 = new Runnable() {

			@Override
			public void run() {
				lockAndConditionDemo.task3();
			}
		};
		for (int i = 0; i < 10; i++) {
			new Thread(run1).start();
			new Thread(run2).start();
			new Thread(run3).start();
		}
	}
}


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