Java 多线程顺序打印ABC

之前看了个题目,利用多线程顺序打印10次ABC,方法有多种,以下也是一种思路。

不过,这样写,循环多少次,就需要创建多少个线程,性能不是很好

package com.thread.chapter1;

public class PrintABC {
    Object lock = new Object();
    boolean isA = true, // 第一次要先打印A,所以默认值为true
            isB = false, isC = false;
    public static void main(String[] args) throws InterruptedException {
        PrintABC printABC = new PrintABC();
        for (int i = 0; i < 10; i++) {
            Thread threadA = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        printABC.printA(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            Thread threadB = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        printABC.printB(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            Thread threadC = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        printABC.printC(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            threadA.start();
            Thread.sleep(100); // 如果不加sleep 100,容易打印不够10次,
                                     // 竞争太厉害,容易造成死锁等待(即isA/isB/isC都为false)
            threadB.start();
            Thread.sleep(100);
            threadC.start();
            Thread.sleep(100);
        }
        System.out.println("main");
    }

    private void printA(String threadName) throws InterruptedException {
        synchronized (lock) {
            while (!isA) {
                lock.wait(); //wait/notify要配合synchronized使用
            }
            System.out.println("A:: "+threadName);
            isA = false;
            isB = true;
            lock.notify();
        }
    }

    private void printB(String threadName) throws InterruptedException {
        synchronized (lock) {
            while (!isB) {
                lock.wait();
            }
            System.out.println("B:: "+threadName);
            isB = false;
            isC = true;
            lock.notify();
        }
    }

    private void printC(String threadName) throws InterruptedException {
        synchronized (lock) {
            while (!isC) {
                lock.wait();
            }
            System.out.println("C:: "+threadName);
            isC = false;
            isA = true;
        }
    }
}

 

你可能感兴趣的:(java)