synchronized 代码块实现,为什么运行不起来;代码如下。
来源:7-7 交替打印

坂田渣渣辉
2019-10-28
public class PrintTest {
private static int count = 0;
private static final Object lock = new Object();
public static void main(String[] args){
System.out.println("start---");
new Thread(new PrintEven(count,lock)).start();
new Thread(new PrintOdd(count,lock)).start();
}
}
/**
* 打印基数线程
*/
class PrintOdd implements Runnable{
int count;
Object lock;
public PrintOdd(int count,Object lock){
this.lock = lock;
this.count =count;
}
@Override
public void run() {
while (count<=100){
synchronized (lock){
if ((count & 1) == 1){
System.out.println(Thread.currentThread().getName()+":"+count++);
}
}
}
}
}
/**
* 打印偶数线程
*/
class PrintEven implements Runnable{
int count;
Object lock;
public PrintEven(int count,Object lock){
this.lock = lock;
this.count =count;
}
@Override
public void run() {
while (count<=100){
synchronized (lock){
if ((count & 1) == 0){
System.out.println(Thread.currentThread().getName()+":"+ count++);
}
}
}
}
}
写回答
1回答
-
你代码里的count是类的变量而不是static,所以一个类里+1之后,第二个类感受不到。你debug就可以看出来。
142019-12-20
相似问题