1、两个线程交替运行
public static void test1() {
new Thread() {
public void run() {
synchronized (Class.class) {
while (true) {
//通知对方
Class.class.notify();
System.out.println("线程一");
try {
//通知完成后进入等待对方唤醒
Class.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
public void run() {
synchronized (Class.class) {
while (true) {
//通知对方
Class.class.notify();
System.out.println("线程二");
try {
//通知完成后进入等待对方唤醒
Class.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
}
2、三个进程间的通信,将notify换成notifyall
public static void test2() {
new Thread() {
public void run() {
synchronized (Class.class) {
while (true) {
Class.class.notifyAll();
System.out.println("线程一");
try {
Class.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
public void run() {
synchronized (Class.class) {
while (true) {
Class.class.notifyAll();
System.out.println("线程二");
try {
Class.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
public void run() {
synchronized (Class.class) {
while (true) {
Class.class.notifyAll();
System.out.println("线程三");
try {
Class.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
}