Java——线程死锁示例

直接代码:

//构造死锁最主要的特点:要是同一把锁,A线程进来了,则B线程进不来。

class Test implements Runnable{
	private boolean flag ;
	
	//构造函数
	Test(boolean flag){
		this.flag = flag;
	}
	
	public void run(){
		//传的是true
		if(flag){
			while(true)
				try{
					Thread.sleep(1);
					synchronized(MyLock.locka){
					System.out.println(Thread.currentThread().getName() + " if locka...");
					
					synchronized(MyLock.lockb){
						System.out.println(Thread.currentThread().getName() + " if lockb...");
					}
				}
				}
				 catch (InterruptedException e){
	
				}
				
		} 
		//传的是true
		else{
			while(true) //所以首先线程1进行运作
				synchronized(MyLock.lockb){
					System.out.println(Thread.currentThread().getName() + " else lockb...");
					synchronized(MyLock.locka){
						System.out.println(Thread.currentThread().getName() + "else locka...");
					}
				
				}
		}	
		
	}
}

class MyLock{
	// 定义了两个常量
	public static final Object locka = new Object();
	public static final Object lockb = new Object();
	
}

public class DeadLockDemo{
	public static void main(String[] args){
		Test a = new Test(true);
		Test b = new Test(false);
		
		Thread t1 = new Thread(a);
		
		Thread t2 = new Thread(b);
		
		t1.start();
		t2.start();
		
	}
}







猜你喜欢

转载自blog.csdn.net/LiLi_code/article/details/86568590