java模拟两个线程锁死


class A{
    public synchronized void foo(B b) {
        String name = Thread.currentThread().getName();
        System.out.println(name + "entered A.foo()");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + " trying to call B.last()");
        b.last();
    }
        public synchronized void last(){
            System.out.println("Insert into A.last()");
        }
}
class B{
    public synchronized void foo(A a){
        String name=Thread.currentThread().getName();
        System.out.println(name+"entered B.foo()");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name+" trying to call A.last()");
        a.last();
    }
    public synchronized void last(){
        System.out.println("Insert into B.last()");
    }
}
public class Deadlock  implements Runnable{

    A a=new A();
    B b=new B();
    public Deadlock(){
        Thread.currentThread().setName("MainThread");
        Thread t=new Thread(this,"RacingThread");
        t.start();
        a.foo(b);
        System.out.println("Back in MainThread");
    }
    @Override
    public void run() {
        b.foo(a);
        System.out.println("enter in other Thread");
    }
}
public static void main(String[] args) throws InterruptedException {
        new Deadlock();
}

输出结果:
java模拟两个线程锁死_第1张图片

你可能感兴趣的:(java,线程,锁死)