一个简单的死锁样例

//关于死锁写法有很多,下面是一个简单的死锁,这里一定要注意若锁是一个对象所,那么多线程的锁的对象一定要是同一个所谓共享的通一把锁,这里刚开始学很容易定义线程对象的时候连续new两个Runnable的对象那么共享的锁不一样。见代码:

package ThreadTest;


class Processor12 implements Runnable{
	Object o1 = new Object();
	Object o2 = new Object();
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(Thread.currentThread().getName().equals("t1")){
			this.sale1();
		}else if(Thread.currentThread().getName().equals("t2")){
			this.sale2();
		}
	}
	public void sale1() {
		// TODO Auto-generated method stub
		synchronized(o2){
			try{
				Thread.sleep(1000);
			}catch(Exception e){
				e.printStackTrace();
			}
			synchronized(o1){
				System.out.println(Thread.currentThread().getName() + "-->" + "this Thread start");
			}
		}
	}
	public void sale2() {
		// TODO Auto-generated method stub
		synchronized(o1){
			try{
				Thread.sleep(1000);
			}catch(Exception e){
				e.printStackTrace();
			}
			synchronized(o2){
				System.out.println(Thread.currentThread().getName() + "-->" + "this Thread start");
			}
	
		}
	}
}

public class ThreadTest12 {

	public static void main(String[] args) throws InterruptedException {
		Processor12 pro = new Processor12();	//就这里连个线程共享同一个实现接口的对象
		Thread t1 = new Thread(pro, "t1");
		Thread t2 = new Thread(pro, "t2");
		t2.start();
		Thread.sleep(500);
		t1.start();
	}
}

猜你喜欢

转载自blog.csdn.net/small__snail__5/article/details/81357026