多线程之Condition

 

 jdk 官网对Condition的描述:

ConditionObject 监视器方法(waitnotifynotifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。

 

下面通过网上一道面试题看看Condition的应用:

   启动三个线程,顺序打印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 PrintABC {
	Lock lock = new ReentrantLock();
	Condition aCdt = lock.newCondition();
	Condition bCdt = lock.newCondition();
	Condition cCdt = lock.newCondition();
	int order = 0;
	public static void main(String[] args) {
		final PrintABC print = new PrintABC();
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 10; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					print.printA();
				}
			});
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					print.printB();
				}
			});
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					print.printC();
				}
			});

		}
		executorService.shutdown();
	}

	public void printA() {
		try {
			lock.lock();
			while (order != 0) {
				aCdt.await();
			}
			System.out.println("A");
			order = 1;
			bCdt.signal();

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void printB() {

		try {
			lock.lock();
			while (order != 1)
				bCdt.await();
			System.out.println("B");
			order = 2;
			cCdt.signal();

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void printC() {

		try {
			lock.lock();
			while (order != 2)
				cCdt.await();
			System.out.println("C");
			order = 0;
			aCdt.signal();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值