对 Threads 有点陌生。
我有 2 个线程并希望它们交替使用一种方法。所以线程 1 执行该方法,然后等待。然后线程 2 唤醒线程 1 并执行该方法。然后线程 1 唤醒线程 2 并执行该方法等。但不知何故我陷入了僵局,我不明白为什么。
public class NewT extends Thread{
public void print(NewT x)
{
synchronized(this)
{
System.out.println("x"+x);
notifyAll();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run()
{
for(int i=0;i<10;i++)
{
print(this);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
NewT one = new NewT();
NewT two = new NewT();
one.start();
two.start();
}
}
九州编程
侃侃尔雅
相关分类