/**
* AB线程交替打印数字
*/
public class PrintAsOrder {
static int i = 0;
static Object sync = new Object();
static class ThreadA extends Thread {
public ThreadA() {
super("ThreadA");
}
@Override
public void run() {
while (i < 100) {
synchronized (sync) {
System.out.println(i + Thread.currentThread().getName());
i++;
sync.notifyAll();
try {
sync.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class ThreadB extends Thread {
public ThreadB() {
super("ThreadB");
}
@Override
public void run() {
while (i < 100) {
synchronized (sync) {
if (i == 0) {
sync.notifyAll();
try {
sync.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i + Thread.currentThread().getName());
i++;
sync.notifyAll();
try {
sync.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new ThreadB().start();
new ThreadA().start();
}
}
网友评论