我一直在聖誕老人的工作坊裏面提出一個問題,在這個工作坊裏,很多事情都必須發生,才能交付禮物。一個這樣的要求是11個精靈成功地生產了100件禮物。我的主類看起來是這樣的:如何正確使用信號燈
public class Main {
public volatile int toyList = 100;
public int getToyList() {
return toyList;
}
public void setToyList(int toyList) {
this.toyList = toyList;
}
public static void main(String[] args){
Main main = new Main();
...
Elf elfOne = new Elf("Jim", main);
Elf elfTwo = new Elf("John", main);
Elf elfThree = new Elf("Eamonn", main);
Elf elfFour = new Elf("Eoin", main);
Elf elfFive = new Elf("Ronan", main);
Elf elfSix = new Elf("Seamus", main);
Elf elfSeven = new Elf("Rebecca", main);
Elf elfEight = new Elf("Orla", main);
Elf elfNine = new Elf("Tina", main);
Elf elfTen = new Elf("Filly", main);
Elf elfEleven = new Elf("Jess", main);
...
elfOne.start();
elfTwo.start();
elfThree.start();
elfFour.start();
elfFive.start();
elfSix.start();
elfSeven.start();
elfEight.start();
elfNine.start();
elfTen.start();
elfEleven.start();
}
和我的精靈類看起來是這樣的:
public class Elf extends Thread{
Semaphore semaphore = new Semaphore(11);
Random rng = new Random();
String name;
Main main;
public Elf(String name, Main main){
this.name = name;
this.main = main;
}
public void run(){
while(true){
try {
semaphore.acquire();
makeToy();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
private void makeToy() throws InterruptedException{
if (main.getToyList() != 0){
if(rng.nextInt(99) <= 4){ //5% chance to fail
System.out.println(name + " failed in making a toy!");
}else{
main.setToyList(main.getToyList() - 1);
System.out.println(name + " created a toy! Toys remaining: " + main.getToyList());
}
} else {
wakeSanta();
}
}
private void wakeSanta() throws InterruptedException {
}
}
示例輸出我得到的是:
...
Eamonn created a toy! Toys remaining: 6
Jim created a toy! Toys remaining: 7
Eoin created a toy! Toys remaining: 8
Jess created a toy! Toys remaining: 9
Filly created a toy! Toys remaining: 0
我想輸出得到的是它會依次遞減一個從100到0的隨機Elf。這是否像我的信號量獲取位置錯誤或者我完全誤解了信號量那樣簡單?
你試圖保護的資源是一個int。除非您的任務明確要求信號量,否則稍後會將玩具列表轉換爲其他結構,使用AtomicInteger也可以完成這項工作。沒有管理信號量的複雜性。 – Ralf 2014-11-25 10:07:19