我正在尝试实现死锁条件,但不知何故我无法让它工作。线程 Thread1 和 Thread2 都进入了 run 函数,但只有一个进入 Sub/Sum 取决于谁先进入 run。示例:如果 Thread2 先进入运行,它将调用 sub(),而 Thread1 从不调用 sum()。我还添加了睡眠时间,以便 Thread2 在调用 sum() 之前睡眠,并且 Thread1 有足够的时间进入 Sum() 但 Thread1 永远不会进入。
public class ExploringThreads {
public static void main(String[] args) {
// TODO Auto-generated method stub
threadexample a1 = new threadexample();
Thread t1 = new Thread(a1, "Thread1");
Thread t2 = new Thread(a1,"Thread2");
t1.start();
t2.start();
}
}
class threadexample implements Runnable{
public int a = 10;
public void run(){
if(Thread.currentThread().getName().equals("Thread1"))
sum();
else if(Thread.currentThread().getName().equals("Thread2"))
sub();
}
public synchronized void sum()
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"In Sum");
sub();
}
public synchronized void sub()
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"In Sub");
sum();
}
}