Condition控制线程通信:java三个线程循环打印ABC

时间:2022-04-29
本文章向大家介绍Condition控制线程通信:java三个线程循环打印ABC,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
private Lock lock = new ReentrantLock();
	private Condition c1 = lock.newCondition();
	private Condition c2 = lock.newCondition();
	private Condition c3 = lock.newCondition();
	private int remark = 1;//

	public static void main(String[] args) throws InterruptedException {
		final ConditionTest test = new ConditionTest();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					test.printA();
				}
	
			}
		}, "A").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					test.printB();
				}
				

			}
		}, "B").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					test.printC();
				}
	
			}
		}, "C").start();

	}

	public void printA() {
		lock.lock();
		if (remark != 1) {
			try {
				c1.await();
			} catch (InterruptedException e) {
			}
		}
		remark = 2;
		c2.signalAll();//依次唤醒下一个需要打印的线程
		System.out.print(Thread.currentThread().getName());
		lock.unlock();
	}

	public void printB() {
		lock.lock();
		if (remark != 2) {
			try {
				c2.await();
			} catch (InterruptedException e) {
			}
		}
		remark = 3;
		c3.signalAll();
		System.out.print(Thread.currentThread().getName());
		lock.unlock();
	}

	public void printC() {
		lock.lock();
		if (remark != 3) {
			try {
				c3.await();
			} catch (InterruptedException e) {
			}
		}
		remark = 1;
		c1.signalAll();
		System.out.print(Thread.currentThread().getName() + "t");
		lock.unlock();
	}