work

  1. package cn.dustray;
  2. import java.util.Random;
  3. public class TestMain {
  4. public static final Object lock = new Object();
  5. public static boolean isGuessDone = false;
  6. public static int bingoNum;
  7. public static void main(String[] args) {
  8. MyRunnable1 ru1 = new MyRunnable1();
  9. new Thread(ru1).start();
  10. MyRunnable2 ru2 = new MyRunnable2();
  11. new Thread(ru2).start();
  12. }
  13. }
  14. class MyRunnable1 implements Runnable {
  15. @Override
  16. public synchronized void run() {
  17. while (!TestMain.isGuessDone)
  18. try {
  19. Thread.sleep(200);
  20. synchronized (TestMain.lock) {
  21. setBingoNum();
  22. }
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. public void setBingoNum() {
  28. Random r = new Random();
  29. TestMain.bingoNum = r.nextInt(99) + 1;
  30. }
  31. }
  32. class MyRunnable2 implements Runnable {
  33. public static final int SMALLER = -1;
  34. public static final int BINGO = 0;
  35. public static final int BIGGER = 1;
  36. @Override
  37. public void run() {
  38. while (!TestMain.isGuessDone)
  39. try {
  40. Thread.sleep(200);
  41. synchronized (TestMain.lock) {
  42. Random r = new Random();
  43. if (judgeNum(r.nextInt(99) + 1)) {
  44. TestMain.isGuessDone = true;
  45. }
  46. }
  47. } catch (InterruptedException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. public boolean judgeNum(int guessNum) {
  52. System.out.print("(" + guessNum + ":" + TestMain.bingoNum + ")");
  53. switch (TestMain.bingoNum < guessNum ? BIGGER : (TestMain.bingoNum == guessNum ? BINGO : SMALLER)) {
  54. case SMALLER:
  55. System.out.println("猜小了");
  56. break;
  57. case BINGO:
  58. System.out.println("猜对了");
  59. return true;
  60. case BIGGER:
  61. System.out.println("猜大了");
  62. break;
  63. }
  64. return false;
  65. }
  66. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值