欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程 死锁的产生与避免

程序员文章站 2022-04-17 14:40:11
...
package thread03;

/**
 * 死锁 : 过多的同步可能造成相互不释放资源
 * 从而互相等待,一般发生于同步中持有多个对象的锁
 * 
 * 避免:不要在同一个代码块中,同时持有多个对象的锁
 * 
 * @author 
 *
 */
public class TestDeadLock {
	public static void main(String[] args) {
		Markup g1 = new Markup(1, "a");
		Markup g2 = new Markup(0, "b");
		g1.start();
		g2.start();
	}
}

//口红
class Lipstick{
	
}

//镜子
class Mirror{
	
}

//化妆
class Markup extends Thread{
	static Lipstick lipstick = new Lipstick();
	static Mirror mirror = new Mirror();
	
	//选择
	int choice;
	//名字
	String girl;
	
	public Markup(int choice, String girl) {
		super();
		this.choice = choice;
		this.girl = girl;
	}


	@Override
	public void run() {
		//化妆
		try {
			makeup();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//相互持有对方的对象锁-->可能造成死锁
	private void makeup() throws InterruptedException {
		if(choice == 0) {
			synchronized(lipstick) {//获得口红的锁
				System.out.println(this.girl+"涂口红");
				//一秒后想拥有镜子
				Thread.sleep(1000);
				
				/*synchronized (mirror) {//获得镜子
					System.out.println(this.girl+"照镜子");
				}*/
			}
			synchronized (mirror) {//获得镜子
				System.out.println(this.girl+"照镜子");
			}
			
		}else{
			synchronized (mirror) {//获得镜子的锁
				System.out.println(this.girl+"照镜子");
				//两秒后想拥有口红的锁
				Thread.sleep(2000);
				
				/*synchronized(lipstick) {
					System.out.println(this.girl+"涂口红");
				}*/
			}
			synchronized(lipstick) {
				System.out.println(this.girl+"涂口红");
			}
		}
	}
}