Home  >  Article  >  Java  >  What is deadlock in java concurrency learning? Introduction to deadlock

What is deadlock in java concurrency learning? Introduction to deadlock

青灯夜游
青灯夜游forward
2018-10-22 17:48:132596browse

This article brings you the content of java concurrency learning: What is a deadlock? Introduction to deadlock. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

  • Introduction to deadlock:
    Lock is a very useful tool with many operating scenarios because it is very simple to use and easy to understand. But at the same time, it will also cause some troubles, such as deadlock problems. For example, there are two threads A and B, both of which require two resources a and b to run. A obtains resource a, and B obtains resource b. Then A requests resource b, and B requests resource a. The two threads block each other and cause a deadlock.

  • Code example:

public calss DeadLockDemo{
	private static String A = "A";
	private static String B = "B";
	public static void main(String[] args){
		new DeadLockdemo().deadLock();
	}
	private void deadLock(){
		Thread t1 = new Thread(new Runnable(){
			@Override
			public void run(){
				synchronized(A){
					try{
						Thread.currentThread().sleep(2000);
					}catch(Exception e){
					  e.printStackTrace();
					 }
					 synchronized(B){
					 	System.out.println("B");
					 }
				}
			}
		});
		Thread t2 = new Thread(new Runnable(){
			@Override
			public void run(){
				synchronized(B){
					try{
						Thread.currentThread().sleep(2000);
					}catch(Exception e){
					  e.printStackTrace();
					 }
					 synchronized(A){
					 	System.out.println("A");
					 }
				}
			}
		});
		t1.start();
		t2.start();
	}
}

A deadlock will occur after the above code is executed, and t1 and t2 block each other.

  • Scenario analysis of deadlock:
    In a more complex scenario, you may encounter such a problem. After t1 gets the lock, due to some abnormal conditions without releasing the lock (infinite loop). Or t1 got a database lock, and when releasing the lock, an exception was thrown but was not released.

  • Several ways to avoid deadlock:
    1. Try to avoid a thread acquiring multiple locks at the same time.
    2. Try to avoid one thread occupying multiple supports at the same time, and try to only occupy one resource at the same time.
    3. Try to use time lock. Lock.tryLock(timeout) instead uses the internal locking mechanism.
    4. For database locks, locking and unlocking must be performed in a database connection.

The above is the detailed content of What is deadlock in java concurrency learning? Introduction to deadlock. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete