1. public class ABCPrint extends Thread {
    2. private final String str[] = {"A", "B", "C"};
    3. private final static AtomicInteger atomCount = new AtomicInteger();
    4. public ABCPrint(String name) {
    5. this.setName(name);
    6. }
    7. @Override
    8. public void run() {
    9. while (true) {
    10. // 循环满2轮退出打印
    11. if (atomCount.get() / 3 == 2) {
    12. break;
    13. }
    14. synchronized (atomCount) {
    15. // 顺序打印A、B、C
    16. if (str[atomCount.get() % 3].equals(getName())) {
    17. atomCount.getAndIncrement();//自增
    18. System.out.println(getName());
    19. //表示一轮打印结束 方便观察打印下分隔符
    20. if ("C".equals(getName())) {
    21. System.out.println("================================");
    22. }
    23. // 当前线程打印打印完成后唤醒其它线程
    24. atomCount.notifyAll();
    25. } else {
    26. // 非顺序线程wait()
    27. try {
    28. atomCount.wait();
    29. } catch (InterruptedException e) {
    30. e.printStackTrace();
    31. }
    32. }
    33. }
    34. }
    35. }
    36. }
    37. public static void main(String[] args) {
    38. new ABCPrint("A").start();
    39. new ABCPrint("B").start();
    40. new ABCPrint("C").start();
    41. }