JAVA concurrent programming 5

Description: Code first, and notes will be added later. 
public class LockTest1 {
/**
* Lock nesting will cause deadlock
* Avoid 1. Try not to write lock nesting 2. Lock nesting order (both call getLock method) 3. Introduce timeout mechanism
*/
//Display lock Lock, reentrant lock
// interruptible lock, Lock is, interruptible
// fair lock, synchronized is a random lock, unfair
// optimistic lock, pessimistic lock database level
Lock lock = new ReentrantLock();

/**
* Read on readerLock and write on WriteLock
*/
ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

//lock locka lockb
private Object locka = new Object();
private Object lockb = new Object();

public static void main(String[] args) {
new LockTest1().deadLock();
}
/**
* 嵌套锁
*/
private void deadLock(){
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
getLock();
// synchronized (locka){
// try {
// System.out.println(Thread.currentThread().getName()+"获取A锁!");
// Thread.sleep(500);
// System.out.println(Thread.currentThread().getName()+"睡眠500ms");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"需要B锁");
// synchronized (lockb){
// System.out.println(Thread.currentThread().getName()+"B锁中!");
// }
// }
}
},"thread1");

Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
getLock();
// synchronized (lockb){
// try {
// System.out.println(Thread.currentThread().getName()+"获取B锁!");
// Thread.sleep(500);
// System.out.println(Thread.currentThread().getName()+"睡眠500ms");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"需要A锁");
// synchronized (locka){
// System.out.println(Thread.currentThread().getName()+"A锁中!");
// }
// }
}
},"thread2");

thread1.start();
thread2.start();
}

public void getLock(){
synchronized (locka){
try {
System.out.println(Thread.currentThread().getName()+"获取A锁!");
Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+"睡眠500ms");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"需要B锁");
synchronized (lockb){
System.out.println(Thread.currentThread().getName()+"B锁中!");
}
}
}
}

Guess you like

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