之前和一个朋友偶尔谈起一道题,图的内容如标题。感觉写的很杂锁,希望大佬提供更好的方法,不胜感激。
代码如下:
package com.loan.common.utils;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author herman
*/
public class AlternateRun implements Runnable {
private int tnum = 1;// 线程编号,Thread Number
private int oneFlag = 0;
// 相等次数
private volatile int eqCount = 0;
// 用重入锁
private ReentrantLock lock = new ReentrantLock();
private Condition oneCon = lock.newCondition();
private Condition twoCon = lock.newCondition();
public static void main(String[] args) {
new AlternateRun().run();
}
public void run() {
new Thread(new OneThread(), "one light").start();
new Thread(new TwoThread(), "two light").start();
}
class OneThread implements Runnable {
public void run() {
while (eqCount < 3) {
try {
lock.lock();
while (tnum != 1) {// 判断是否该自己执行了[采用while不是if是为了防止死锁]
// 不是1 自己等待
oneCon.await();
}
if (eqCount < 3) {
// 随机生成1-6正整数
oneFlag = new Random().nextInt(6) + 1;
System.out.println(Thread.currentThread().getName() + " oneFlag = " + oneFlag);
TimeUnit.MILLISECONDS.sleep(100);// 停留时间,便于从控制台观看
tnum = 2;
// 唤醒第二个线程
twoCon.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
class TwoThread implements Runnable {
public void run() {
while (eqCount < 3) {
try {
lock.lock();
while (tnum != 2) {
twoCon.await();
}
if (eqCount < 3) {
// 随机生成1-6正整数
int twoFlag = new Random().nextInt(6) + 1;
System.out.println(Thread.currentThread().getName() + " twoFlag = " + twoFlag);
if (twoFlag == oneFlag) {
System.out.println("又一次相等-------------");
eqCount++;
}
TimeUnit.MILLISECONDS.sleep(100);// 停留时间,便于从控制台观看
tnum = 1;
oneCon.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
}
谢谢,希望大佬提供更好的办法。
- 作为小菜鸟难免很多地方理解不到位,文中若有错误请直(bu)接(yao)指(ma)出(wo)