package cn.dustray;
import java.util.Random;
public class TestMain {
public static final Object lock = new Object();
public static boolean isGuessDone = false;
public static int bingoNum;
public static void main(String[] args) {
MyRunnable1 ru1 = new MyRunnable1();
new Thread(ru1).start();
MyRunnable2 ru2 = new MyRunnable2();
new Thread(ru2).start();
}
}
class MyRunnable1 implements Runnable {
@Override
public synchronized void run() {
while (!TestMain.isGuessDone)
try {
Thread.sleep(200);
synchronized (TestMain.lock) {
setBingoNum();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setBingoNum() {
Random r = new Random();
TestMain.bingoNum = r.nextInt(99) + 1;
}
}
class MyRunnable2 implements Runnable {
public static final int SMALLER = -1;
public static final int BINGO = 0;
public static final int BIGGER = 1;
@Override
public void run() {
while (!TestMain.isGuessDone)
try {
Thread.sleep(200);
synchronized (TestMain.lock) {
Random r = new Random();
if (judgeNum(r.nextInt(99) + 1)) {
TestMain.isGuessDone = true;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean judgeNum(int guessNum) {
System.out.print("(" + guessNum + ":" + TestMain.bingoNum + ")");
switch (TestMain.bingoNum < guessNum ? BIGGER : (TestMain.bingoNum == guessNum ? BINGO : SMALLER)) {
case SMALLER:
System.out.println("猜小了");
break;
case BINGO:
System.out.println("猜对了");
return true;
case BIGGER:
System.out.println("猜大了");
break;
}
return false;
}
}
work
最新推荐文章于 2022-06-20 17:46:55 发布