Semaphore 信號量-0
1.構造方法
同步關鍵類 Semaphore
permits 是允許許可的意思
構造方法傳入的數字是多少,則同一個時刻,只運行多少個進程同時運行指定代碼
指定代碼就是 在 semaphore.acquire() 和 semaphore.release()之間的代碼
private Semaphore semaphore = new Semaphore(2);
package com.lhc.concurrent.semaphore;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Semaphore;
public class ConstructionService {
private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* 同步關鍵類
* permits 是允許許可的意思
* 構造方法傳入的數字是多少,則同一個時刻,只運行多少個進程同時運行指定代碼
* 指定代碼就是 在 semaphore.acquire() 和 semaphore.release()之間的代碼
*/
private Semaphore semaphore = new Semaphore(2);
public void doSomething() {
try {
/**
* 在 semaphore.acquire() 和 semaphore.release()之間的代碼,同一時刻只允許指定個數的線程進入,
* 因爲semaphore的構造方法是1,則同一時刻只允許一個線程進入,其他線程只能等待。
* */
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + ":開始執行,時間:" + getFormatTimeStr());
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + ":執行結束,時間:" + getFormatTimeStr());
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String getFormatTimeStr() {
return sf.format(new Date());
}
}
2.測試類
package com.lhc.concurrent.semaphore;
public class SemaphoreThread extends Thread{
private ConstructionService constructionService;
public SemaphoreThread(ConstructionService constructionService, String name) {
super();
this.constructionService = constructionService;
this.setName(name);
}
public static void main(String[] args) {
ConstructionService constructionService = new ConstructionService();
for (int i = 0; i < 10; i++) {
SemaphoreThread semaphoreThread = new SemaphoreThread(constructionService, "線程" + i);
semaphoreThread.start();
}
}
@Override
public void run() {
constructionService.doSomething();
}
}
3.執行結果
線程0:開始執行,時間:2019-04-13 10:08:44.290
線程1:開始執行,時間:2019-04-13 10:08:44.290
線程1:執行結束,時間:2019-04-13 10:08:46.294
線程0:執行結束,時間:2019-04-13 10:08:46.294
線程3:開始執行,時間:2019-04-13 10:08:46.294
線程2:開始執行,時間:2019-04-13 10:08:46.294
線程2:執行結束,時間:2019-04-13 10:08:48.306
線程3:執行結束,時間:2019-04-13 10:08:48.306
線程5:開始執行,時間:2019-04-13 10:08:48.306
線程6:開始執行,時間:2019-04-13 10:08:48.306
線程6:執行結束,時間:2019-04-13 10:08:50.318
線程5:執行結束,時間:2019-04-13 10:08:50.318
線程4:開始執行,時間:2019-04-13 10:08:50.318
線程7:開始執行,時間:2019-04-13 10:08:50.318
線程7:執行結束,時間:2019-04-13 10:08:52.320
線程4:執行結束,時間:2019-04-13 10:08:52.320
線程8:開始執行,時間:2019-04-13 10:08:52.320
線程9:開始執行,時間:2019-04-13 10:08:52.320
線程9:執行結束,時間:2019-04-13 10:08:54.324
線程8:執行結束,時間:2019-04-13 10:08:54.324