2012-09-30 59 views
0

我想創建一個小程序,演示使用信號量。我創建了2個線程,運行Farmer的兩個實例:一個以字符串「north」作爲參數,另一個以「south」作爲參數。相反,具有1周線程完成,隨後第二,他們似乎都在同一時間(如indictated由輸出完成:信號量不會工作

農民要過了橋,向北
農民要過了橋,向南
農民已經過了橋,現在向北
農民已經過了橋,現在向南

誰能告訴我什麼I'm做錯了什麼?

import java.util.concurrent.Semaphore; 
public class Farmer implements Runnable 
{ 
    private String heading; 
    private final Semaphore bridge = new Semaphore(1); 
    public Farmer(String heading) 
    { 
     this.heading = heading; 
    } 

    public void run() 
    { 
     if (heading == "north") 
     { 
      try 
      { 
       //Check if the bridge is empty 
       bridge.acquire(); 
       System.out.println("Farmer going over the bridge, heading north"); 
       Thread.sleep(1000); 
       System.out.println("Farmer has crossed the bridge and is now heading north"); 
       bridge.release(); 
      } 
      catch (InterruptedException e) 
      { 
       e.printStackTrace(); 
      } 
      //Farmer crossed the bridge and "releases" it 

     } 
     else if (heading == "south") 
     { 
      try 
      { 
       //Check if the bridge is empty 
       bridge.acquire(); 
       System.out.println("Farmer going over the bridge, heading south"); 
       Thread.sleep(1000); 
       //Farmer crossed the bridge and "releases" it 
       System.out.println("Farmer has crossed the bridge and is now heading south"); 
       bridge.release(); 
      } 
      catch (InterruptedException e) 
      { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
+1

此外,您正在使用==來進行字符串比較,這絕不是一個好主意。你應該使用'equals(...)'。我看到「北」和「北」 – Gray

回答

4

每個農民都在創建自己的信號量,這意味着它可以獨立於任何其他人獲取和發佈它。

更改此:

private final Semaphore bridge = new Semaphore(1); 

這樣:

private final static Semaphore bridge = new Semaphore(1); 

然後旗語將所有農民實例之間共享。

+0

啊,當然!多麼愚蠢的錯誤。非常感謝你! – Anubis

+0

沒問題。在那裏,做到了,擁有許多相關的T恤...... –