某一个同步块同时拥有“两个以上对象的锁”时,就可能发生"死锁"的问题
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
MakeUp q1 = new MakeUp(0,"黑哥");
MakeUp q2 = new MakeUp(1,"白鸽");
q1.start();
q2.start();
}
}
class Lipstick{
}
class Mirror{
}
class MakeUp extends Thread{
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;
}
@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.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+"获得镜子的锁");
}
}
}
}
package com.hanbin.syn;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
MakeUp q1 = new MakeUp(0,"黑哥");
MakeUp q2 = new MakeUp(1,"白鸽");
q1.start();
q2.start();
}
}
class Lipstick{
}
class Mirror{
}
class MakeUp extends Thread{
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;
}
@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.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+"获得镜子的锁");
}
}
}
}
}
之需要将syn代码块内的锁拿出来,即可
定义一个lock锁
private final ReentrantLock lock = new ReentrantLock();
try{
lock.lock();//上锁
}finally{
//解锁
lock.unlock();
}