public class SingelDoublechange {
private static final Object object=new Object();
private static int num = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread1=new Thread(new Single(num,object));
Thread thread2=new Thread(new Double(num,object));
thread2.start();
// Thread.sleep(10);
thread1.start();
}
}
class Single implements Runnable{
private int num;
Object object;
public Single(int num,Object object){
this.num=num;
this.object=object;
}
@Override
public void run() {
while(num<100) {
synchronized (object) {
if (num % 2 != 0) {
System.out.println(num + "是奇数");
num++;
}
}
}
}
}
class Double implements Runnable{
private int num;
Object object;
public Double(int num,Object object){
this.num=num;
this.object=object;
}
@Override
public void run() {
while (num<100) {
synchronized (object){
if (num % 2 == 0) {
System.out.println(num + "是偶数");
num++;
}
}
}
}
}
结果就是只输出一个0 然后卡住了