odmedabs 2013-01-01 16:21
浏览 276
已采纳

以下代码,semaphore会不会引起一些同步的问题(重入),需要修改吗

[code="java"]
package learn;
import java.util.concurrent.Semaphore;
class applePlate{
static Semaphore apple = new Semaphore(2);
static Semaphore space = new Semaphore(3);
}

class Eater implements Runnable{
String name;
Object o;
Eater(String name, Object o){
this.name = name;
this.o = o;
}
public void run(){
int count = 4;
while(count-- > 0){

            try{
                applePlate.apple.acquire();
            }catch(InterruptedException e){
                throw new RuntimeException(e);
            }
            applePlate.space.release();
            System.out.println("Eater " + name +" eat"+"   :left " 
                    + applePlate.apple.availablePermits());

    }
}

}

class Producer implements Runnable{
String name;
Object o;
Producer(String name, Object o){
this.name = name;
this.o = o;
}

public void run(){
    int count = 3;
    while(count-- > 0){

            try{
                applePlate.space.acquire();
            }catch(InterruptedException e){
                throw new RuntimeException(e);
            }
            applePlate.apple.release();
            System.out.println("Producer " + name +" produce"+"   :left " 
                    + applePlate.apple.availablePermits());

    }
}

}

class Go {
public static void main(String args[]){
Object o = new Object();
Eater e1 = new Eater("eee", o), e2 = new Eater("eee2", o);
Producer p1 = new Producer("ppp", o), p2 = new Producer("ppp2", o);
Thread th1 = new Thread(e1);
Thread th2 = new Thread(e2);
Thread th3 = new Thread(p1);
Thread th4 = new Thread(p2);
th1.start();
th2.start();
th3.start();
th4.start();
}
}
[/code]

  • 写回答

2条回答 默认 最新

  • u010589844 2013-01-02 15:01
    关注

    信号量只是在信号不够的时候挂起线程,但是并不能保证信号量足够的时候获取对象和返还对象是线程安全的。所以你还需要有Lock来保证并发的正确性。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?