标题: 关于同步代码块的问题,怎么避免输出81? [打印本页] 作者: yangben 时间: 2016-6-2 22:32 标题: 关于同步代码块的问题,怎么避免输出81? 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;
}*/