过多的同步可能会造成 相互不释放资源 相互的等待 然后造成死锁
代码如下:
public class SnyTest {
public static void main(String[] args) {
Markup markup1 = new Markup(0,"大丫");
Markup markup2 = new Markup(1,"二丫");
markup1.start();
markup2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
//化妆
class Markup extends Thread{
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
//选择
int choice;
//名字
String girl;
public Markup(int choice,String girl){
this.choice=choice;
this.girl =girl;
}
public void run(){
//化妆
markup();
}
//相互持有对方的对象锁 ---》可能造成死锁
private void markup(){
if(choice ==0){
synchronized (lipstick){ //获得口红的锁 同时想获取镜子的锁
System.out.println(this.girl +"获得口红");
//一秒后想拥有镜子的锁
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (mirror){
System.out.println(this.girl +"获得镜子");
}
}
}else{
synchronized (mirror){ //获得镜子的锁 同时想获取口红的锁
System.out.println(this.girl +"获得镜子");
//一秒后想拥有镜子的锁
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lipstick){
System.out.println(this.girl +"获得口红");
}
}
}
}
}
解决方法如下 改进:(不要进行锁嵌套 即可解决 )
private void markup(){
if(choice ==0){
synchronized (lipstick) { //获得口红的锁 不要进行锁嵌套
System.out.println(this.girl + "获得口红");
}
//一秒后想拥有镜子的锁
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (mirror){
System.out.println(this.girl +"获得镜子");
}
}else{
synchronized (mirror) { //获得口红的锁 不要进行锁嵌套
System.out.println(this.girl + "获得镜子");
}
//一秒后想拥有镜子的锁
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lipstick){
System.out.println(this.girl +"获得口红");
}
}
}