[关闭]
@Yano 2017-07-31T12:54:32.000000Z 字数 1769 阅读 2596

Java多线程,循环打印”ABC”10次

面试题


思路

3个线程A,B,C分别打印三个字母,每个线程循环10次,首先同步,如果不满足打印条件,则调用wait()函数一直等待;之后打印字母,更新state,调用notifyAll(),进入下一次循环。

代码

  1. public class printABC {
  2. private static int state = 0;
  3. public static void main(String[] args) {
  4. final printABC t = new printABC();
  5. Thread A = new Thread(new Runnable() {
  6. public void run() {
  7. // 设定打印10次
  8. for (int i = 0; i < 10; i++) {
  9. synchronized (t) {
  10. // 如果不满足A的打印条件,则调用wait,一直阻塞
  11. while (state % 3 != 0) {
  12. try {
  13. t.wait();
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. // 执行到这里,表明满足条件,打印A,设置state
  19. // 调用notifyAll方法
  20. System.out.print("A");
  21. state++;
  22. t.notifyAll();
  23. }
  24. }
  25. }
  26. });
  27. Thread B = new Thread(new Runnable() {
  28. public void run() {
  29. for (int i = 0; i < 10; i++) {
  30. synchronized (t) {
  31. while (state % 3 != 1) {
  32. try {
  33. t.wait();
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. System.out.print("B");
  39. state++;
  40. t.notifyAll();
  41. }
  42. }
  43. }
  44. });
  45. Thread C = new Thread(new Runnable() {
  46. public void run() {
  47. for (int i = 0; i < 10; i++) {
  48. synchronized (t) {
  49. while (state % 3 != 2) {
  50. try {
  51. t.wait();
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. System.out.println("C");
  57. state++;
  58. t.notifyAll();
  59. }
  60. }
  61. }
  62. });
  63. A.start();
  64. B.start();
  65. C.start();
  66. }
  67. }

2017年07月31日 更新

最近看到了原来写的博客,觉得当时写得并不是很好,重新写了一下,记录之。

  1. package test;
  2. public class PrintABC {
  3. private static final int PRINT_A = 0;
  4. private static final int PRINT_B = 1;
  5. private static final int PRINT_C = 2;
  6. private static class MyThread extends Thread {
  7. int which; // 0:打印A;1:打印B;2:打印C
  8. static volatile int state; // 线程共有,判断所有的打印状态
  9. static final Object t = new Object();
  10. public MyThread(int which) {
  11. this.which = which;
  12. }
  13. @Override
  14. public void run() {
  15. for (int i = 0; i < 10; i++) {
  16. synchronized (t) {
  17. while (state % 3 != which) {
  18. try {
  19. t.wait();
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. System.out.print(toABC(which)); // 执行到这里,表明满足条件,打印
  25. state++;
  26. t.notifyAll(); // 调用notifyAll方法
  27. }
  28. }
  29. }
  30. }
  31. public static void main(String[] args) {
  32. new MyThread(PRINT_A).start();
  33. new MyThread(PRINT_B).start();
  34. new MyThread(PRINT_C).start();
  35. }
  36. private static char toABC(int which) {
  37. return (char) ('A' + which);
  38. }
  39. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注