今天看到一段關(guān)于synchronized的小代碼,比較有意思。當(dāng)將S1的static去掉,這個(gè)死鎖便解開(kāi)了。其實(shí)也很好理解,線(xiàn)程1進(jìn)入后鎖住S1,并且等待了500,在等待時(shí)線(xiàn)程2來(lái)了,鎖住了S2。線(xiàn)程1的500過(guò)了后接著鎖住S2開(kāi)始下面的輸出,但是S2被線(xiàn)程2鎖住不放;同樣線(xiàn)程2鎖住了S2,接著去取S1的控制權(quán),但是線(xiàn)程1卻握著不放。死鎖便產(chǎn)生了。S1和S2都是static關(guān)鍵字修飾,他們都是共享內(nèi)存空間,去掉這個(gè)關(guān)鍵字,那么線(xiàn)程1和線(xiàn)程2鎖住的不是同一個(gè)對(duì)象了,問(wèn)題也不會(huì)產(chǎn)生。每個(gè)對(duì)象都包含了一把鎖(也叫作“監(jiān)視器”),它自動(dòng)成為對(duì)象的一部分(不必為此寫(xiě)任何特殊的代碼)。調(diào)用任何synchronized方法時(shí),對(duì)象就會(huì)被鎖定,不可再調(diào)用那個(gè)對(duì)象的其他任何synchronized方法,除非第一個(gè)方法完成了自己的工作,并解除鎖定。
package com.example.thread2;
public class TestDeadLock implements Runnable {
public int flag = 1;
static Object S1 = new Object();
static Object S2 = new Object();
public String threadId;
public TestDeadLock(String s){
threadId = s;
}
public void run() {
System.out.println(threadId + ":flag=" + flag);
if (flag == 1) {
synchronized (S1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (S2) {
System.out.println("1");
}
}
}
if (flag == 0) {
synchronized (S2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (S1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock("No.1");
TestDeadLock td2 = new TestDeadLock("No.2");
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
public class TestDeadLock implements Runnable {
public int flag = 1;
static Object S1 = new Object();
static Object S2 = new Object();
public String threadId;
public TestDeadLock(String s){
threadId = s;
}
public void run() {
System.out.println(threadId + ":flag=" + flag);
if (flag == 1) {
synchronized (S1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (S2) {
System.out.println("1");
}
}
}
if (flag == 0) {
synchronized (S2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (S1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock("No.1");
TestDeadLock td2 = new TestDeadLock("No.2");
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}