【问题标题】:Working with Binary Semaphore [closed]使用二进制信号量[关闭]
【发布时间】:2012-11-28 18:36:15
【问题描述】:

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

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

我是从信号量类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 是的

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

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

【问题讨论】:

  • 我没有看到围绕 println 语句的任何循环。你能显示丢失的代码吗?
  • 剩下的就是测试类和信号量类,我稍后将在我需要制作的第三个线程中使用它们。测试类只创建了 2 个信号量 x 和 y 以及两个线程 x 和 y,它启动它们并运行它们 10 秒。
  • 好吧,每个线程只调用一次println。所以,我不希望代码打印出其他任何内容。
  • 应该关闭,因为dsfdfdsfdfsdsfsddsfdsfdsfdsfsdfdsfdsfsdfsfdfsdfds 似乎不是一个非常强烈的问题

标签: java multithreading concurrency java.util.concurrent


【解决方案1】:

这是因为您的线程只打印一次然后被终止,就像@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"); 
    }
  }
}   

【讨论】:

  • 是的,这正是我在 cmets 中所说的。
  • @reprogrammer 是的,我在提交答案后就注意到了您的第二条评论。
  • 谢谢 dan 和 @reprogrammer 非常感谢。我知道我错过了一些简单的事情,并且专注于信号量而不是线程本身。
猜你喜欢
  • 1970-01-01
  • 2017-10-03
  • 2011-07-29
  • 1970-01-01
  • 2015-11-16
  • 2020-12-23
  • 2022-11-01
  • 2018-04-17
  • 2012-10-07
相关资源
最近更新 更多