手写多线程交替打印ABC

手写多线程交替打印ABC

package com.demo.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class syncPrinter implements Runnable{
	 // 打印次数
	 private static final int PRINT_COUNT = 10;
	 private final ReentrantLock reentrantLock;
	 private final Condition thisCondtion;
	 private final Condition nextCondtion;
	 private final char printChar;
	 public syncPrinter(ReentrantLock reentrantLock, Condition thisCondtion, Condition nextCondition, char
	printChar) {
		this.reentrantLock = reentrantLock;
	 	this.nextCondtion = nextCondition;
	 	this.thisCondtion = thisCondtion;
	 	this.printChar = printChar;
	 }
	 @Override
	 public void run() {
	 	// 获取打印锁 进入临界区
	 	reentrantLock.lock();
	 	try {
	 		// 连续打印PRINT_COUNT次
	 		for (int i = 0; i < PRINT_COUNT; i++) {
			 	//打印字符
			 	System.out.print(printChar);
			 	// 使用nextCondition唤醒下一个线程
			 	// 因为只有一个线程在等待,所以signal或者signalAll都可以
			 	nextCondtion.signal();
			 	// 不是最后一次则通过thisCondtion等待被唤醒
			 	// 必须要加判断,不然虽然能够打印10次,但10次后就会直接死锁
			 	if (i < PRINT_COUNT - 1) {
				 	try {
				 		// 本线程让出锁并等待唤醒
				 		thisCondtion.await();
				 	} catch (InterruptedException e) {
				 		e.printStackTrace();
				 	}
			 	}
		 	}
		 } finally {
		 	reentrantLock.unlock();
		 }
	 }
	
	 public static void main(String[] args) throws InterruptedException {
		 ReentrantLock lock = new ReentrantLock();
		 Condition conditionA = lock.newCondition();
		 Condition conditionB = lock.newCondition();
		 Condition conditionC = lock.newCondition();
		 Thread printA = new Thread(new syncPrinter(lock, conditionA, conditionB,'A'));
		 Thread printB = new Thread(new syncPrinter(lock, conditionB, conditionC,'B'));
		 Thread printC = new Thread(new syncPrinter(lock, conditionC, conditionA,'C'));
		 printA.start();
		 Thread.sleep(100);
		 printB.start();
		 Thread.sleep(100);
		 printC.start();
	 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值