1、死锁实例
Java线程死锁是一个经典的多线程问题,因为不同的线程都在等待根本不可能被释放的锁,从而导致所有的任务都无法继续完成。在多线程技术中,“死锁”是必须避免的,因为这会造成线程的“假死”。- public class DeathThread implements Runnable {
- public String username;
- public Object lock1 = new Object();
- public Object lock2 = new Object();
- public void setFlag(String username) {
- this.username = username;
- }
- public void run() {
- if (username.equals(“a”)) {
- synchronized (lock1) {
- try {
- System.out.println(”username = ” + username);
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized (lock2) {
- System.out.println(”按lock1->lock2代码顺序执行了”);
- }
- }
- }
- if (username.equals(“b”)) {
- synchronized (lock2) {
- try {
- System.out.println(”username = ” + username);
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized (lock1) {
- System.out.println(”按lock1->lock2代码顺序执行了”);
- }
- }
- }
- }
- }
public class DeathThread implements Runnable {
public String username;
public Object lock1 = new Object();
public Object lock2 = new Object();
public void setFlag(String username) {
this.username = username;
}
public void run() {
if (username.equals("a")) {
synchronized (lock1) {
try {
System.out.println("username = " + username);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("按lock1->lock2代码顺序执行了");
}
}
}
if (username.equals("b")) {
synchronized (lock2) {
try {
System.out.println("username = " + username);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("按lock1->lock2代码顺序执行了");
}
}
}
}
}
- public class Run {
- public static void main(String[] args) throws InterruptedException {
- DeathThread deathThread = new DeathThread();
- deathThread.setFlag(”a”);
- Thread thread1 = new Thread(deathThread);
- thread1.start();
- Thread.sleep(1000);
- deathThread.setFlag(”b”);
- Thread thread2 = new Thread(deathThread);
- thread2.start();
- }
- }
public class Run {
public static void main(String[] args) throws InterruptedException {
DeathThread deathThread = new DeathThread();
deathThread.setFlag("a");
Thread thread1 = new Thread(deathThread);
thread1.start();
Thread.sleep(1000);
deathThread.setFlag("b");
Thread thread2 = new Thread(deathThread);
thread2.start();
}
}
username = a username = b |
死锁是程序设计的Bug.在设计程序时就要避免双方互相持有对方的锁的情况。需要说明的是,本实验使用synchronized嵌套的代码结构来实现死锁,其实不使用嵌套的synchronized代码结构也会出现死锁,与嵌套不嵌套无任何的关系,不要被代码结构所误导。
产生死锁的四个必要条件: (1) 互斥条件:一个资源每次只能被一个进程使用。 (2) 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。 (3) 不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。 (4) 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。