多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致俩个或者多个线程都在等待对方释放资源。
package syn;
public class DeadLock {
public static void main(String[] args) {
Makeup s1 = new Makeup(0,"小明");
Makeup s2 = new Makeup(1,"小红");
s1.start();
s2.start();
}
}
class Lipstick {
}
class Mirror {
}
class Makeup extends Thread{
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String name;
Makeup(int choice, String name){
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if(choice == 0){
synchronized (lipstick){
System.out.println(this.name+"拿到了口红的锁");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");
}
}
}else {
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(this.name+"拿到了口红的锁");
}
}
}
}
}
只要将一把锁改为俩把锁就可以释放资源
package syn;
public class DeadLock {
public static void main(String[] args) {
Makeup s1 = new Makeup(0,"小明");
Makeup s2 = new Makeup(1,"小红");
s1.start();
s2.start();
}
}
class Lipstick {
}
class Mirror {
}
class Makeup extends Thread{
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String name;
Makeup(int choice, String name){
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if(choice == 0){
synchronized (lipstick){
System.out.println(this.name+"拿到了口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");
}
}else {
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){
System.out.println(this.name+"拿到了口红的锁");
}
}
}
}
标签:name,synchronized,Makeup,System,choice,死锁,out
From: https://www.cnblogs.com/gang-pao/p/18141771