【发布时间】: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