关于java中线程死锁的例子

package Test;

public class DieSock {
 //	Single s1 = Single.getSingle();
//	Single s2 = Single.getSingle();
	static Test t1 = new Test();

	public static void main(String[] args) {
		new Thread(t1).start();
		new Thread(t1).start();
	}
}

class Test implements Runnable{
	static Object obj1 = new Object();
	static Object obj2 = new Object();
	private Singles s = Singles.getSingle();
	private int testNum = 100;
	@Override
	public void run() {
		while(testNum > 0){
			synchronized(obj1){			//一个线程执行到这里,发现obj2被另一个线程使用,因此等待
				synchronized(obj2){
					testNum = s.getNum()-1;
					s.setNum(testNum);
					System.out.println(testNum);
				}
			}
			synchronized(obj2){
				synchronized(obj1){		//一个线程执行到这里,发现obj1被另一个线程使用,因此等待,所以互相锁住了
					testNum = s.getNum()-1;
					s.setNum(testNum);
					System.out.println(testNum);
				}
			}
		}
		
	}
	
}

class Singles {
	private int num = 100;
	private static Singles singles = new Singles();
	private Singles(){}
	static Singles getSingle(){
		return singles;
	}
	public int getNum(){
		return num;
	}
	public void setNum(int num){
		this.num = num;
	}
}



    原文作者:java锁
    原文地址: https://blog.csdn.net/qa275267067/article/details/80336958
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞