多執行緒之死鎖、生產者與消費者模型以及執行緒池
阿新 • • 發佈:2021-06-29
-
互斥條件:一個資源每次只能被一個程序使用
-
請求與保持條件:一個程序因請求資源而阻塞時,對已獲得的資源保持不放
-
不剝奪條件:程序已獲得的資源,在未使用完之前,不能強制剝奪
-
例項
package com.yeyue.thread;
public class DeadLock {
public static void main(String[] args) {
new Makeup(0,"灰姑涼").start();
new Makeup(1,"白雪公主").start();
}
}
//口紅
class Lipstick{
}
//鏡子
class Mirror {
}
class Makeup extends Thread {
//需要的資源只有一份,用static來保證只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String girlName;
Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
避免死鎖
package com.yeyue.thread;
public class DeadLock {
public static void main(String[] args) {
new Makeup(0,"灰姑涼").start();
new Makeup(1,"白雪公主").start();
}
}
//口紅
class Lipstick{
}
//鏡子
class Mirror {
}
class Makeup extends Thread {
//需要的資源只有一份,用static來保證只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String girlName;
Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
synchronized與lock的對比
-
lock是顯示鎖(手動開啟和關閉鎖,別忘記關鎖)synchronized是隱式鎖,除了作用域自動釋放
-
lock只有程式碼塊鎖,synchronized有程式碼塊鎖和方法鎖
-
使用lock鎖,jvm將花費較少的時間來排程執行緒,效能更好。而且具有更好的擴充套件性(提供更多的子類)
-
優先使用順序:
lock>同步程式碼塊(已經進入方法體,分配了相應資源)>同步方法(在方法體之外)
例項
package com.yeyue.thread;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
//定義lock鎖
private final ReentrantLock lock = new ReentrantLock();
生產者消費者模型-->利用緩衝區解決:管程法
package com.yeyue.thread;
//測試:生產者消費者模型-->利用緩衝區解決:管程法
//生產者,消費者,產品,緩衝區
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生產者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
//生產