package com.umbrella.container.queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadTest {
static Lock lock = new ReentrantLock();
static Condition w = lock.newCondition();
static Condition n = lock.newCondition();
static boolean isW = false;
public void printW() {
try {
lock.lock();
while (!isW) {
w.await();
}
System.out.println("w");
n.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printN() {
try {
lock.lock();
while (isW) {
n.await();
}
System.out.println("n");
w.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
new Thread(() -> {
t.printW();
}, "w").start();
new Thread(() -> {
t.printN();
}, "n").start();
}
}用lock锁 想要做成两个线程交替输出 但老是搓的 哪里错了啊
添加回答
举报
0/150
提交
取消