背景
小編可開心啦,屁顛屁顛的把ExecutorService executor = Executors.newSingleThreadExecutor();單例線程的方案給說出來啦;順便把代碼也貼上。
SingleThreadExecutor 實現
package com.evan.springboot.study;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author evanYang
* @version 1.0
* @date 2020/5/26 上午 10:41
*/
public class ExecutorDemos {
public static void main(String[] args) {
Thread a = new Thread(){
@Override
public void run() {
System.out.println("thread a 執行");
try {
Thread.sleep(200);
System.out.println("執行ing。。。。。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread b = new Thread(){
@Override
public void run() {
System.out.println("thread b 執行");
try {
Thread.sleep(200);
System.out.println("執行ing。。。。。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread c = new Thread(){
@Override
public void run() {
System.out.println("thread c 執行");
System.out.println("執行ing。。。。。");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(a);
executor.execute(b);
executor.execute(c);
executor.shutdown();
}
}
我們可以看到這裏了是按照順序執行啦;很開心有木有;
面試官: 你這不就是個單線程執行嗎? 有木有其他更好的idea呢?
不知道小夥伴們有沒有更好的想法呢
基於信號量(Semaphore)實現
-
Lock和synchronized是鎖的互斥,一個線程如果鎖定了一個資源,那麼其他線程只能等待資源的釋放。也就是一次只有一個線程執行,直到這個線程執行完畢或者unlock。而Semaphore可以控制多個線程同時對每個資源的訪問。Semaphore實現的功能就類似廁所有5個坑,假如有10個人要上廁所,那麼同時只能有多少個人去上廁所呢?
同時只能有5個人能夠佔用,當五個人中的任何一個人讓開後,其中等待的另外5個人又有一個人可以佔用了
。另外等待的5個人是可以隨機的獲取優先機會,也可以是按照先來後到的順序獲得機會,這取決於構造Semaphore對象時傳入的參數選項。當然單個信號量的Semaphore對象可以實現互斥鎖的功能,並且可以是由一個線程獲得了鎖,再由另外一個線程釋放鎖,這塊引用於死鎖恢復的一些場合。 -
信號量用在多線程多任務多任務同步的,一個線程完成了某一個動作就通過信號量告訴別的線程,別的線程在進行某些動作。也就是說Semaphore不一定是鎖定某個資源,而是流程上的概念。比方說有A,B兩個線程,B線程的操作可能要等A線程執行完畢之後才執行,這個任務
並不一定是鎖定某一資源,還可以是進行一些計算或者數據處理之類,它們也許並不訪問共享變量,只是邏輯上的先後順序。 -
java計數信號量(Semaphore)維護着一個許可集。調用acquire()獲取一個許可,release()釋放一個許可。在java中,還可以設置該信號量是否採用公平模式,如果以公平方式執行,則線程將會按到的的順序(FIFO)執行,如果是非公平,則可以後請求的有可能排在隊列的頭部。
Semaphore當前在多線程環境下被擴放使用,操作系統的信號量是個很重要的概念,在進程控制方面都有運用。java併發庫Semaphore可以很輕鬆完成信號量控制,Semaphore可以控制某個資源可被同時訪問的個數。
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
final Semaphore semaphore = new Semaphore(5);
for (int index = 0; index < 20; index++) {
final int NO = index;
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"Accessing:" + NO);
Thread.sleep((long) (Math.random() * 10000));
semaphore.release();
System.out.println("------------------" + semaphore.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executorService.execute(runnable);
}
executorService.shutdown();
}