死锁
源代码①:
package cn.ecut.lock;
/*
死锁:
多个资源各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,
而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个
同步块同时拥有“两个以上对象的锁”时 ,就可能会发生死锁的问题
*/
//死锁
public class DeadLock2 {
public static void main(String[] args) {
Makeup2 g1=new Makeup2(0,"小红");
Makeup2 g2=new Makeup2(1,"小黄");
g1.start();
g2.start();
}
}
//口红
class Lipstick2{
}
//镜子
class Mirror2{
}
class Makeup2 extends Thread{
//控制资源只有一份,用static来保证
static Lipstick2 lipstick=new Lipstick2();
static Mirror2 mirror=new Mirror2();
int choice;//选择
String girlName;//使用化妆品的人
public Makeup2(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup2() throws InterruptedException {
if(choice==0){
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
}
}
}
else{
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
@Override
public void run() {
try {
makeup2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
源代码②:
package cn.ecut.lock;
//解决死锁的方法原则
public class DeadLock {
public static void main(String[] args) {
Makeup g1=new Makeup(0,"小红");
Makeup g2=new Makeup(1,"小黄");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//控制资源只有一份,用static来保证
static Lipstick lipstick=new Lipstick();
static Mirror mirror=new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
public Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if(choice==0){
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
}
}
else{
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果①:
运行结果②: