我有一个关于管理线程的简单问题。我有3个程序共享同一个信号量和一个许可证。在正常情况下,第一个过程需要此许可证,并在第二个过程中发布两个许可证。第二个流程版本3允许第三个流程。我举了一个例子来说明我的问题。使用信号量造成死锁
第一招:
public class Process0 extends Thread{
Semaphore s;
public Process0(Semaphore s){
this.s = s;
}
public void run(){
try {
sleep(20000);
s.acquire();
System.out.println("hello");
} catch (InterruptedException ex) {
Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
}
s.release(2);
}
}
第二个过程:
public class Process1 extends Thread{
Semaphore s;
public Process1(Semaphore s){
this.s = s;
}
public void run(){
try {
this.sleep(10000);
s.acquire(2);
System.out.println("Hello 2");
} catch (InterruptedException ex) {
Logger.getLogger(Process1.class.getName()).log(Level.SEVERE, null, ex);
}
s.release(3);
}
}
还有最后一:
public class Process2 extends Thread{
Semaphore s;
public Process2(Semaphore s){
this.s = s;
}
public void run(){
try {
System.out.println("Acquire process 3 ");
s.acquire(3);
System.out.println("Hello 3");
} catch (InterruptedException ex) {
Logger.getLogger(Process2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
的问题。当我运行这三个过程并确保过程3是第一个执行acquire
。我会陷入僵局。进程2从不打印“Hello 3”,进程1从不打印“Hello 2”。为什么?
信号量s =新的信号量(1);
Process0 p = new Process0(s);
Process1 p1 = new Process1(s);
Process2 p2 = new Process2(s);
p.start();
p1.start();
p2.start();
您如何确保流程3首先获得它?首先启动并不意味着它会先执行。对于这个问题,睡觉也没有。 – zubergu
我在获取Process和Process1 – Mehdi
之前添加睡眠,可能会或可能无法完成您想要的操作。根据线程执行顺序来设计应用程序从一开始就是错误的。 – zubergu