避免死锁方法--使用tryLock方法
package com.chen.test.Thread.AvoidDeadLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* 避免线程死锁方式:
* 1、资源分配顺序是有序的
* 2、破坏死锁必要条件
* 3、使用tryLock()方法,tryLock()带返回值的,返回是boolean类型,如果是true说明是获得锁,否则获得锁失败,
* 与此同时,也可以使用tryLock(long time,TimeUtil.time util)有参方法,设置规定时间,如果在指定时间范围内没有获得锁或者是遇到阻塞
*/
public class TryLockDemo3 {
private static final Logger log = LoggerFactory.getLogger(TryLockDemo3.class);
private final ReentrantLock lock1 = new ReentrantLock();
private final ReentrantLock lock2 = new ReentrantLock();
public void service(){
long id = Thread.currentThread().getId();
String name = Thread.currentThread().getName();
while (true){
if(id % 2 ==0){
try {
if (lock1.tryLock()){
log.info(name + " get lock1 lock success ! ");
Thread.sleep(10);
try {
if(lock2.tryLock()){
log.info(name + " start works !");
for (int i = 0; i < 3; i++) {
log.info(name + " i = " + i);
}
return;
}
}finally {
if(lock2.isHeldByCurrentThread()){
log.info(name + " release lock2 lock !");
lock2.unlock();
}
}
}
}catch (InterruptedException ver1){
log.error(name + "Throws exception and print exceptions !");
ver1.printStackTrace();
}finally {
if (lock1.isHeldByCurrentThread()){
log.info(name + " release lock1 lock !");
lock1.unlock();
}
}
}else {
try {
if (lock1.tryLock()){
log.info(name + " get lock1 lock success ! ");
Thread.sleep(500);
try {
if(lock2.tryLock()){
log.info(name + " start works !");
for (int i = 0; i < 3; i++) {
log.info(name + " i = " + i);
}
return;
}
}finally {
if(lock2.isHeldByCurrentThread()){
log.info(name + " release lock2 lock !");
lock2.unlock();
}
}
}
}catch (InterruptedException ver1){
log.error(name + "Throws exception and print exceptions !");
ver1.printStackTrace();
}finally {
if (lock1.isHeldByCurrentThread()){
log.info(name + " release lock1 lock !");
lock1.unlock();
}
}
}
}
}
//main method
public static void main(String[] args) {
TryLockDemo3 demo3 = new TryLockDemo3();
try {
for (int i = 0; i < 10; i++) {
new Thread(demo3::service,"Thread-" +i).start();
}
Thread.sleep(1000);
}catch (InterruptedException ver1){
ver1.printStackTrace();
}
}
}
|