2

你好,我有一个小问题,不知道我哪里出了问题。

我有 2 个线程 X 重复打印 X 和 Y 重复打印 Y。Y 需要在 X 之后打印。

我从 Semaphore 类 BinarySemaphore 派生:

public class BinarySemaphore extends Semaphore {

public BinarySemaphore(int initial){
    value = (initial>0) ? 1 : 0;
}

public synchronized void P() throws InterruptedException{
    while (value==0){
    wait();
    }
value = 0;
    notify();
}

public synchronized void V(){

    value = 1;
    notify();
}
}

X 线程类

public class xThread extends Thread implements Runnable{

private BinarySemaphore xSemaphore;
private BinarySemaphore ySemaphore;


public xThread(String myName, BinarySemaphore nSemaphoreX, BinarySemaphore nSemaphoreY ){
    super(myName);
    xSemaphore = nSemaphoreX;
    ySemaphore = nSemaphoreY;
}

public void run(){
    try{
    xSemaphore.P();
    System.out.println(getName());
    ySemaphore.V();
    }catch(InterruptedException E){
    System.out.println("Thread X was interrupted"); 
    }
}   
}

Y 螺纹类

public class yThread extends Thread implements Runnable{

private BinarySemaphore xSemaphore;
private BinarySemaphore ySemaphore;


public yThread(String myName, BinarySemaphore nSemaphoreX, BinarySemaphore nSemaphoreY ){
    super(myName);
    xSemaphore = nSemaphoreX;
    ySemaphore = nSemaphoreY;
}

public void run(){
    try{
    ySemaphore.P();
    System.out.println(getName());
    xSemaphore.V();
    }catch(InterruptedException E){
    System.out.println("Thread Y was interrupted");
    }


}
}

当我运行这些线程 10 秒时,我得到的只是

X Y

构建成功(总时间:10 秒)

我在这里想念什么?为什么不让它们交替 10 秒?

4

1 回答 1

0

这是因为您的线程只打印一次然后被终止,就像@reprogrammer 在他的评论中建议的那样。您应该插入一个循环,例如:

public void run(){
  while (needsToRun){
    try{
    xSemaphore.P();
    System.out.println(getName());
    ySemaphore.V();
    }catch(InterruptedException E){
    System.out.println("Thread X was interrupted"); 
    }
  }
}   
于 2012-11-28T18:43:52.857 回答