理解高併發(3).多線程開發常見問題示例

多線程開發過程中,經常會出現的一些問題:非線程安全、死鎖、飢餓鎖。 示例代碼如下:

  • 非線程安全

package com.zuche.thread.demo1;

public class TestClient {
public static void main(String[] args) {
final Account account = new Account(1000);
Thread t = new Thread(new Runnable(){
public void run() {
account.add(20);
}
});
Thread t1 = new Thread(new Runnable(){
public void run() {
account.withdraw(20);
}
});
t.start();
t1.start();
System.out.println("最後的金額:" + account.getBalance());
}
}
理論上最後的金額應該爲1000


  • 死鎖
package com.zuche.thread.demo3;

public class WorkThread extends Thread{
private String adjustMoney = "adjustMoney";
private String work = "work";
private String ruleType;
public WorkThread(String ruleType){
this.ruleType = ruleType;
}
public void run(){
if(ruleType.equals("employee")){
employeeSay();
}
if(ruleType.equals("boss")){
bossSay();
}
}
private void employeeSay(){
synchronized(adjustMoney){
System.out.println("員工說,先調薪後幹活");
synchronized (work) {
System.out.println("員工調薪順利調薪,開始帶勁的幹活");
}
}
}
private void bossSay(){
synchronized(work){
System.out.println("老闆說,先給我好好的幹活再來談加薪的事兒");
synchronized(adjustMoney){
System.out.println("活幹的不錯,可以適當的考慮加點錢");
}
}
}
}
運行後,程序不能正常退出,卡死在那兒。
死鎖概念: 2個線程相互僵持不下,導致無法訪問共享資源,最終無法釋放鎖資源。


  • 飢餓鎖
package com.zuche.thread.demo2;

public class Toilet{
public synchronized void doStaff(){
System.out.println(Thread.currentThread().getName() + " begin.");
clean();
while(true){
System.out.println(Thread.currentThread().getName() + " doing.");
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void clean(){
}
}
運行後,另一個線程無法訪問共享資源
飢餓鎖概念: 一個線程佔用着鎖不放導致其它線程無法訪問共享資源
發佈了83 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章