概念
Java中线程死锁的概念:
线程A占用某个锁a的同时并尝试占用锁b,而线程B占用某个锁b的同时并尝试占用锁a,这种情况变会出现死锁。如图所示:
例子
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ThreadTask1 extends Thread{
@Override
public void run() {
try {
ReentrantLockExample.lock1.lock();
System.out.println(this.getName() +" run task");
ReentrantLockExample.lock2.lock();
} catch (Exception e) {
e.printStackTrace();
} finally {
ReentrantLockExample.lock1.unlock();
ReentrantLockExample.lock2.unlock();
}
System.out.println(this.getName() + "run complete");
}
}
class ThreadTask2 extends Thread{
@Override
public void run() {
try {
ReentrantLockExample.lock2.lock();
System.out.println(this.getName() +" run task");
ReentrantLockExample.lock1.lock();
} catch (Exception e) {
e.printStackTrace();
} finally {
ReentrantLockExample.lock2.unlock();
ReentrantLockExample.lock1.unlock();
}
System.out.println(this.getName() + "run complete");
}
}
public class ReentrantLockExample extends Thread {
public static Integer count=1;
public static final Lock lock1 = new ReentrantLock();
public static final Lock lock2 = new ReentrantLock();
public static void main(String args[]) throws InterruptedException {
ThreadTask1 task1 = new ThreadTask1();
ThreadTask2 task2 = new ThreadTask2();
task1.start();
task2.start();
}
}
运行以上代码,程序不会退出,并发生了死锁,如图所示:
如何避免死锁
在对象的同步方法中避免调用其它对象的同步方法即可。