GitHub -> DajinPang

Men just want to be hard !

两个线程交替打印(wait/notify)

public class Alternately {
private volatile Boolean preIsA = false;

synchronized void backA() {
try {
while (preIsA == true) {
wait();
}
for (int i = 0; i < 5; i++) {
System.out.println("💗💗💗💗💗");
}
preIsA = true;
notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

synchronized void backB() {
try {
while (preIsA == false) {
wait();
}
for (int i = 0; i < 5; i++) {
System.out.println("🌙🌙🌙🌙🌙");
}
preIsA = false;
notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
//Thread A = new Thread(()-> backA());
}

@Test
public void testMethod() {
for (int i = 0; i < 5; i++) {
Thread A = new Thread(() -> backA());
Thread B = new Thread(() -> backB());
A.start();
B.start();
}

}

}

posted @ 2019-05-08 22:52  StevenPang  阅读(771)  评论(0)    收藏  举报