三个线程打印ABC.md 1.1 KB

public void print(String str, int target) throws InterruptedException {
    for (int i = 0; i < n; i++) {
        synchronized (obj) {
            while (state % 3 != target) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            state++;
            System.out.print(str);
            obj.notifyAll();
        }
    }
}

public void print(String str, int target) throws InterruptedException {
    for (int i = 0; i < n; ) {
        synchronized (obj) {
            while (state % 3 != target) {
                obj.wait();
            }
            state++;
            i++;
            System.out.print(str);
            obj.notifyAll();
        }
    }
}
public void print(String str, int target) throws InterruptedException {
    for (int i = 0; i < n; ) {
        try {
            lock.lock();
            while (state % 3 == target) {
                System.out.print(str);
                state++;
                i++;
            }
        } finally {
            lock.unlock();
        }
    }
}