死鎖:
過多的同步造成相互不釋放資源,從而過多地等待,一般發(fā)生于
同步中持有多個對象的鎖

潮州ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!
snchronized鎖住對象同時,另一個snchronized就不能鎖該對象
避免在一個代碼塊中,同時持有多個對象的鎖
死鎖:
public class tt {
public static void main(String[]args)
{
markup m1=new markup(1,"me");
markup m2 =new markup(2,"she");
m1.start();
m2.start();
}
}
//口紅
class lipstick{
}
//鏡子
class mirror{
}
//化妝
class markup extends Thread{
//加靜態(tài)表示一份,不管創(chuàng)建幾個對象都是一份
static lipstick lip=new lipstick();
static mirror mir=new mirror();
//選擇
int choice;
String girl;
public markup(int choice,String girl)
{
this.choice=choice;
this.girl=girl;
}
public void run(){
mark();
}
//相互持有對方的對象鎖-->可能造成死鎖
//加等待時間是為了讓另一個線程鎖相同對象的時候,該線程
//鎖的相同對象還沒有結(jié)束
//在這個死鎖中,第一個線程內(nèi)的mir要等第二個已經(jīng)開始的mir鎖結(jié)束才能執(zhí)行
//而第二個線程內(nèi)的mir結(jié)束需要等第一個線程內(nèi)的lip解鎖才行
private void mark()
{
if(choice==0)
{
synchronized(lip)
{
System.out.println(this.girl+"獲得口紅");
//一秒后想要鏡子
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(mir)
{
System.out.println(this.girl+"獲得鏡子");
}
}
}else
{
synchronized(mir)
{
System.out.println(this.girl+"獲得鏡子");
//2秒后想要口紅
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(lip)
{
System.out.println(this.girl+"獲得口紅");
}
}
}
}
}解決:
public class tt {
public static void main(String[]args)
{
markup m1=new markup(1,"me");
markup m2 =new markup(2,"she");
m1.start();
m2.start();
}
}
//口紅
class lipstick{
}
//鏡子
class mirror{
}
//化妝
class markup extends Thread{
//加靜態(tài)表示一份,不管創(chuàng)建幾個對象都是一份
static lipstick lip=new lipstick();
static mirror mir=new mirror();
//選擇
int choice;
String girl;
public markup(int choice,String girl)
{
this.choice=choice;
this.girl=girl;
}
public void run(){
mark();
}
{
if(choice==0)
{
synchronized(lip)
{
System.out.println(this.girl+"獲得口紅");
//一秒后想要鏡子
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized(mir)
{
System.out.println(this.girl+"獲得鏡子");
}
}else
{
synchronized(mir)
{
System.out.println(this.girl+"獲得鏡子");
//2秒后想要口紅
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized(lip)
{
System.out.println(this.girl+"獲得口紅");
}
}
}
}
標(biāo)題名稱:java多線程-死鎖的產(chǎn)生以及解決方案
網(wǎng)頁鏈接:http://www.chinadenli.net/article34/gpdcse.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、微信公眾號、微信小程序、關(guān)鍵詞優(yōu)化、品牌網(wǎng)站建設(shè)、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)