瞭解synchronized同步鎖可以參考
synchronized給併發操作加一把鎖
網上那些背書式的理論知識我也記不住,我只知道一句話,你先把你的給我,我就把我的給你.
要想形成死鎖,首當其衝的就是搶佔資源
demo:
1.先建一個deadlocktest包 (習慣了在包下寫demo…)
2.新建一個資源類Resource
包含一個由synchronized 修飾的同步方法
package deadlocktest;
public class Resource {
private int cpu;
public synchronized void printCpu() {//同步塊->鎖住的商店
System.out.println(Thread.currentThread().getName()+":"+this.cpu++);
}
}
3.新建實現Runnable接口的ThreadMy類
package deadlocktest;
public class ThreadMy implements Runnable{
private Resource resource1;
private Resource resource2;
public ThreadMy(Resource resource1,Resource resource2){
//1.兩個資源
this.resource1=resource1;
this.resource2=resource2;
}
@Override
public void run() {
if (Thread.currentThread().getName().equals("ThreadA")) {
synchronized (resource1) {//2.你一個
try {
Thread.sleep(1000);//休眠下讓另一個線程有足夠時間上鎖
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resource2.printCpu();
}
}if (Thread.currentThread().getName().equals("ThreadB")) {
synchronized (resource2) {//3.我一個
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resource1.printCpu();
}
}
}
}
代碼很簡單,這裏就對主要代碼進行解析
- 想要形成死鎖,至少要有兩個資源,於是構造函數傳入兩個Resource對象
2.在線程run的時候,給ThreadA一個resource1的鎖,給ThreadB一個resource2的鎖
3.sleep休眠是爲了讓另一個線程有足夠時間上鎖
4.新建main函數測試類
package deadlocktest;
public class DeadLockTest {
/**
* @param args
*/
public static void main(String[] args) {
Resource resource1=new Resource();
Resource resource2=new Resource();
new Thread(new ThreadMy(resource1,resource2),"ThreadA").start();//傳入相同的兩個資源實例
new Thread(new ThreadMy(resource1,resource2),"ThreadB").start();
}
}
運行:
如圖,沒有輸出 (還以爲會報錯。。所以死鎖後果很嚴重,是不會報錯的)