線程的死鎖的代碼
/*
?* 死鎖:過多的同步可能造成相互不釋放資源
?* 從而相互等待,一般發(fā)生于同步中持有多個對象的鎖
?* 如何解決:不要在同一個代碼塊中,同時持有多個對象的鎖
?* 第二個鎖在第一個鎖里面才能造成死鎖
?*/
public class DeadLock {
?? ?public static void main(String[] args) {
?? ??? ?Makeup g1 = new Makeup(1, "哈哈");
?? ??? ?Makeup g2 = new Makeup(0, "呵呵");
?? ??? ?g1.start();
?? ??? ?g2.start();
?? ?}
}
//口紅
class Lipstick {
}
//鏡子
class Mirror {
}
//化妝
class Makeup extends Thread {
?? ?// 表示一面口紅和一個鏡子
?? ?static Lipstick lipstick = new Lipstick();
?? ?static Mirror mirror = new Mirror();
?? ?// 選擇
?? ?int choice;
?? ?// 名字
?? ?String girl;
?? ?public Makeup(int choice, String girl) {
?? ??? ?this.choice = choice;
?? ??? ?this.girl = girl;
?? ?}
?? ?@Override
?? ?public void run() {
?? ??? ?// 化妝
?? ??? ?makeup();
?? ?}
?? ?// 相互持有對方的對象鎖-->可能造成死鎖
?? ?private void makeup() {
?? ??? ?if (choice == 0) {
?? ??? ??? ?synchronized (lipstick) {// 獲得口紅的鎖
?? ??? ??? ??? ?System.out.println(this.girl + "涂口紅");
?? ??? ??? ??? ?// 1秒后想擁有鏡子的鎖
?? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ?Thread.sleep(1000);
?? ??? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ??? ?}
?? ??? ??? ??? ?
?? ??? ??? ?}
?? ??? ??? ?synchronized (mirror) {
?? ??? ??? ??? ?System.out.println(this.girl + "照鏡子");
?? ??? ??? ?}
?? ??? ?} else {
?? ??? ??? ?synchronized (mirror) {// 獲得口紅的鎖
?? ??? ??? ??? ?System.out.println(this.girl + "照鏡子");
?? ??? ??? ??? ?// 1秒后想擁有口紅的鎖
?? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ?Thread.sleep(1000);
?? ??? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ??? ?}
?? ??? ??? ??? ?
?? ??? ??? ?}
?? ??? ??? ?synchronized (lipstick) {
?? ??? ??? ??? ?System.out.println(this.girl + "涂口紅");
?? ??? ??? ?}
?? ??? ?}
?? ?}
}
標(biāo)簽: