About thread safety

2016.12.01

 

It will start tomorrow. I can't read a book at all, so let's write code. Now I want to lay a solid foundation, so I have to read the book myself.

Java's synchronization mechanism solves the problem of thread safety, but it also causes deadlock.

The root cause of the deadlock phenomenon is

1. There are two or more threads.

2. There are two or more shares.

There is no solution to the deadlock phenomenon, only avoidance.

The following is implemented with a piece of code.

class DeadLock extends Thread{
	
	public DeadLock(String name){
		super(name);//It is equivalent to calling the constructor of the parent class, without this, the parent class cannot be initialized
	}
	
	
	public void run() {
		if("庹成".equals(Thread.currentThread().getName())){
			synchronized ("remote control") {
				System.out.println("Tuocheng got the remote control, ready to get the battery!!");
				synchronized ("电池") {
					System.out.println("Tuocheng got the remote control and battery, and the air conditioner is blowing coolly...");
				}
			}
		}else if("崔宝文".equals(Thread.currentThread().getName())){
			synchronized ("电池") {
				System.out.println("Cui Baowen got the battery, ready to get the remote control!!");
				synchronized ("remote control") {
					System.out.println("Cui Baowen got the remote control and battery, and the air conditioner is blowing coolly...");
				}
			}
			
		}	
	}
		
}

public class Demo2 {

	public static void main(String[] args) {
		DeadLock d1 = new DeadLock("庹成");
		DeadLock d2 = new DeadLock("崔宝文");
		// start the thread
		d1.start();
		d2.start();	
	}	
}

  The running result will appear:

  Tuo Cheng got the remote control, ready to get the battery!!

  Cui Baowen got the battery and was going to get the remote control!!

  Nope. .

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326850708&siteId=291194637