public class Demo27_2 {
/**
* 模拟三个老师分发80份试卷,三个老师轮着发,每个老师相当于一个线程
*/
public static void main(String[] args) {
final work3 w3 = new work3();
new Thread() {
public void run() {
try {
w3.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
w3.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
w3.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
class work3 {
int flag = 1;
int num = 1;
public void print1() throws InterruptedException{
while (num < 80) {
synchronized (this) {
/*if (num > 80) {
return;
}*/
while (flag != 1) {
this.wait();
}
System.out.println("张老师发了第" + num++ + "份试卷!");
flag = 2;
this.notifyAll();
}
}
}
public void print2() throws InterruptedException{
while (num < 80) {
synchronized (this) {
/*if (num > 80) {
return;
}*/
while (flag != 2) {
this.wait();
}
System.out.println("李老师发了第" + num++ + "份试卷!");
flag = 3;
this.notifyAll();
}
}
}
public void print3() throws InterruptedException{
while (num < 80) {
synchronized (this) {
/*if (num > 80) {
return;
}*/
while (flag != 3) {
this.wait();
}
System.out.println("王老师发了第" + num++ + "份试卷!");
flag = 1;
this.notifyAll();
}
}
}
}
|
|