面试题--三个线程循环打印ABC10次的几种解决方法-wait/notify(1)

面试题--三个线程循环打印ABC10次的几种解决方法-wait/notify(1)
 

package com.ces.myThread;

public class PrintThreadExample implements Runnable {
    private String name;
    private Object pre;
    private Object self;
    private Thread thread;

    public PrintThreadExample(String name, Object pre, Object self) {
        this.name = name;
        this.pre = pre;
        this.self = self;
        thread = new Thread(this, name);
    }

    @Override
    public void run() {
        int count = 3; //2次
        while (count > 0) {
            synchronized (pre) {
                synchronized (self) {
                    System.out.print(name);
                    count--;
                    self.notify();
                }
                try {
                    pre.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();

        PrintThreadExample threadA = new PrintThreadExample("A", c, a);
        PrintThreadExample threadB = new PrintThreadExample("B", a, b);
        PrintThreadExample threadC = new PrintThreadExample("C", b, c);

        threadA.thread.start();
//        Thread.sleep(2);
        threadB.thread.start();
//        Thread.sleep(2);
        threadC.thread.start();
//        Thread.sleep(2);
    }
}

你可能感兴趣的:(面试题--三个线程循环打印ABC10次的几种解决方法-wait/notify(1))