Semaphore 表示信號量,在Linux的信號量的出現是爲了解決共享資源競爭的問題。
其核心概念是:
當請求一個使用信號量來表示的資源時,進程需要先讀取信號量的值來判斷資源是否可用。大於0,資源可以請求,等於0,無資源可用,進程會進入睡眠狀態直至資源可用。
當進程不再使用一個信號量控制的共享資源時,信號量的值+1,表示釋放資源,其它進程就可以使用。
舉例:
public class SemaphoreTest {
public static void main(String[] args) {
// 使用信號量來表示資源。比如現在有3臺電腦,有10個學生用。
int N = 10; // 學生數
int C = 3; // 電腦數
Semaphore semaphore = new Semaphore(C);
for(int i = 0; i < N; i++) {
new Student(i, semaphore).start();
}
}
}
public class Student extends Thread{
private Semaphore semaphore;
private int i;
public Student(int i, Semaphore semaphore) {
this.semaphore = semaphore;
this.i = i;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println("學生" + i + "正在使用電腦..");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("學生" + i + "已經使用完電腦..");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
運行結果:
學生0正在使用電腦..
學生1正在使用電腦..
學生2正在使用電腦..
學生0已經使用完電腦..
學生2已經使用完電腦..
學生1已經使用完電腦..
學生4正在使用電腦..
學生3正在使用電腦..
學生5正在使用電腦..
學生4已經使用完電腦..
學生5已經使用完電腦..
學生3已經使用完電腦..
學生7正在使用電腦..
學生6正在使用電腦..
學生8正在使用電腦..
學生7已經使用完電腦..
學生6已經使用完電腦..
學生9正在使用電腦..
學生8已經使用完電腦..
學生9已經使用完電腦..