執行緒執行時通過JUC獲取鎖的小工具

2021-10-06 20:45:25 字數 1878 閱讀 9674

/**

* 可重入鎖,synchronized和reentrantlock 都是可重入鎖

* synchronized不需要手動解鎖 異常或者執行完自動釋放,reentrantlock需要手動解鎖

* reentrantlock可以設定公平非公平並且可以獲取鎖的狀態嘗試獲取鎖並且可以打斷

* 乙個是jvm鎖物件 乙個是juc的工具 底層採用的cas

*/public class reentralloackdemp catch (exception ex) finally }}

public static void main(string args) throws interruptedexception

for (thread thread : threads)

for (thread thread : threads)

system.out.println(demp.count);

}}/**

* 讀共享鎖 讀執行緒鎖允許其他讀執行緒繼續讀取

* 寫排他鎖 寫執行緒的鎖不允許其他執行緒操作。 排他鎖又叫獨佔鎖

* 和資料庫鎖不一樣, 雖然概念差不多 但是乙個是資料庫乙個是操作記憶體中兩者沒有關係

*/public class testreadwritelock

public static void read(lock lock) catch (interruptedexception e) finally

}public static void write(lock lock, int i) catch (interruptedexception e) finally

}public static void main(string args)

for (int i = 0; i < 2; i++) new thread(()-> write(write, 1)).start();

}}/**

* 倒數計數器 和 join功能差不多 相當於乙個計數小工具

*/public class countdownlatchdemo

public static void main(string args) throws interruptedexception

countdownlatch.await();

system.out.println("所有的都已經執行完畢");

}}/**

* cyclicbarrier是柵欄操作,await()方法呼叫一次計數加1,只有當滿了20之後 才會執行構造方法的後續操作。

*/public class cyclicbarriertest );

public static void main(string args) catch (interruptedexception e) catch (brokenbarrierexception e)

}).start();}}

}public class testsemaphore catch (interruptedexception e)

semaphore.release();

system.out.println(thread.currentthread().getname()+ "當前執行緒執行之後。。");

}, "t1").start();

new thread(()-> catch (interruptedexception e)

semaphore.release();

system.out.println(thread.currentthread().getname()+ "當前執行緒執行之後。。");

}, "t2").start();

}}還有phaser類和exchanger類

獲取程式的執行時間

c c 中的計時函式是clock 而與其相關的資料型別是clock t。在msdn中,查得對clock函式定義如下 clock t clock void 這個函式返回從 開啟這個程式程序 到 程式中呼叫clock 函式 時之間的cpu時鐘計時單元 clock tick 數,在msdn中稱之為掛鐘時間...

獲取執行時類的結構

通過反射建立對應的執行時類的物件 public void test1 throws illegalacces ception,instantiationexception 獲取執行時類的方法結構 public class methodtest system.out.println getdeclar...

Linux C獲取系統的執行時間

sysinfo結構保持了系統啟動後的資訊,主要包括啟動到現在的時間,可用記憶體空間 共享記憶體空間 程序的數目等。man sysinfo得到結果如下所示 struct sysinfo 通過sysinfo獲取系統啟動到現在的秒數,include include include include incl...