JUC併發工具使用案例

2021-10-06 03:34:56 字數 1815 閱讀 1902

包含以下併發工具的呼叫

synchronized 同步鎖

reentrantlock 同步鎖

condition 執行緒通訊

reentrantreadwritelock 讀寫鎖 讀寫分離

stampedlock 讀寫鎖 (悲觀 樂觀) 讀的同時可以寫

atomicinteger 原子性遞增

longadder 分段式鎖 (分段累加 最後彙總)

countdownlatch 同步計數器

cyclicbarrier 迴圈柵欄

phaser 階段器 對所有註冊的執行緒內進行分段阻塞

semaphore 計數訊號器 (限流作用)

exchanger 交換器

locksupport 控制線程阻塞與喚醒

先寫個main方法及主方法介面

public class threadmain 

}inte***ce maininte***ce

synchronized同步鎖

class synclass implements maininte***ce  catch (interruptedexception e) 

lock.unlock();

}}).start();

new thread(new runnable() catch (exception e)

lock.unlock();

}}).start();

}}

reentrantreadwritelock讀寫鎖 讀寫分離,可以同時讀,寫互斥

class readwritelockclass implements maininte***ce 

});thread threads = new thread[30];

for (int i=0;iphaser階段器 分階段阻塞執行緒

重寫phaser類中onadvance方法,初始化執行緒時進行註冊phaser.register(),實現分階段阻塞,類似於運動員比賽過程,

全員到齊->第一場比賽->第二場比賽

class phaserclass extends phaser implements maininte***ce catch (exception e)

system.out.println(this + equitment);

}}).start();

new thread(new runnable() catch (exception e)

system.out.println(this + equitment);

}}).start();

}}

locksupport

呼叫locksupport.park()阻塞執行緒 呼叫locksupport.unpark(thread) 喚醒執行緒,類似於condition

class locksupportclass implements maininte***ce ;

string b = new string;

thread t1,t2;

@override

public void mainmethod() throws exception

}});

t2 = new thread(new runnable()

}});

t1.start();

t2.start();

}}

JUC併發工具類

countdownlatch允許乙個或多個執行緒等待其他執行緒完成操作 具體分析 countdownlatch的建構函式接收乙個int型別的引數作為計數器,而int具體數值則代表要等待多少個執行緒點的完成!例如,程式中初始設定為2,則表示等待的數量為2.然後就是,countdownlatch的cou...

JUC併發程式設計

併發程式設計的本質 充分利用cpu的資源 執行緒就是乙個單獨的資源類,沒有任何的附屬操作。傳統的synchronize鎖本質 佇列,鎖 lock.lock 加鎖 trynew reentrantlock lock.lock 加鎖 finally lock.unlock 解鎖鎖是什麼,如何判斷鎖的是誰...

juc併發程式設計

public class thraedtest string.valueof i start countdownlatch.await system.out.println 關門結束 訊號量通常用來限制執行緒數,比如限流,而不是訪問某些 物理或邏輯 資源。例如,這是乙個使用訊號量來控制對乙個專案池的...