package com.wkcto.chapter07.sync.p6;
public class SubThread extends Thread {
@Override
public void run() {
if ("a".equals(Thread.currentThread().getName())) {
synchronized ("資源1") {
System.out.println("線程a獲得了資源1, 還想獲得資源2");
synchronized ("資源2") {
System.out.println("線程a同時獲得了資源1與資源2,可以做愛做的事了");
}
}
}
if ("b".equals(Thread.currentThread().getName())) {
synchronized ("資源2") {
System.out.println("線程b獲得了資源2, 還想獲得資源1");
synchronized ("資源1") {
System.out.println("線程b同時獲得了資源1與資源2,可以做愛做的事了");
}
}
}
}
}
package com.wkcto.chapter07.sync.p6;
/**
* 死鎖
* 在線程同步時, 由于線程獲得鎖的順序不一致,導致了線程出現(xiàn)相互等待的情況
* 如何避免死鎖?
* 線程如果想要獲得多個鎖對象, 保證獲得鎖對象的順序一致
* @author 蛙課網(wǎng)
*
*/
public class Test {
public static void main(String[] args) {
SubThread ta = new SubThread();
ta.setName("a");
ta.start();
SubThread tb = new SubThread();
tb.setName("b");
tb.start();
}
}
總結(jié):
理解線程的相關(guān)概念
掌握創(chuàng)建線程的方式
理解線程的生命周期
掌握線程的常用方法
start()
Thread.currentThread
getName() ???/ ?setName()
Thread.sleep()
理解線程同步必須使用同一個鎖對象, 常用的鎖對象: 常量 , this, 當前類的運行時類
理解同步方法,
努力掌握生產(chǎn)者消費者設計模式
掌握Timer定時器類