2012-09-30 53 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恤...... –