以下程序为了学习而写
两个线程依次按序打印从1到100,一个只打印奇数,另一个只打印偶数。但是经常发生死锁,请问为什么
public class Test16 implements Runnable{
private int turn;
private int num;
private int sum;
static Integer counter=0;
public Test16(int turn,int num,int sum){
this.turn=turn;
this.num=num;
this.sum=sum;
}
public synchronized void run() {
while(counter<sum){
while(turn!=counter%num){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
counter++;
System.out.print(counter+" ");
notifyAll();
}
}
public static void main(String[] args){
new Thread(new Test16(0,2,100)).start();
new Thread(new Test16(1,2,100)).start();
}
}