java面试题---请用多线程写死锁

java面试题---用多线程写死锁

(请参考本博客对同步锁的文章进行理解)
public class dead {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadOne one=new ThreadOne();
		ThreadTwo two=new ThreadTwo();
		sharing obj1=new sharing();
		sharing obj2=new sharing();
		one.obj1=obj1;
		one.obj2=obj2;
		two.obj1=obj1;
		two.obj2=obj2;
		one.obj1=two.obj2;
		one.obj2=two.obj1;
	
		one.start();
		two.start();
	}

}
class sharing{
	
}
class ThreadOne extends Thread{
	sharing obj1;
	sharing obj2;
	public void run(){
		synchronized (obj1) {
			System.out.println("我进入了ThreadOne外部锁");
			synchronized (obj2) {
				System.out.println("我进入了ThreadOne内部锁");
			}
		}
	}
}
class ThreadTwo extends Thread{
	sharing obj1;
	sharing obj2;
	public void run(){
		synchronized (obj1) {
			System.out.println("我进入了ThreadTwo外部锁");
			synchronized (obj2) {
				System.out.println("我进入了ThreadTwo内部锁");
			}
		}
	}
}
打印输出:
我进入了ThreadOne外部锁
我进入了ThreadTwo外部锁
(两个线程都在等在同步资源释放自己的锁,一直处于等待状态)

你可能感兴趣的:(Java初级研究)