我的目标是让许多线程访问静态属性“nbPlace”,并将其递减。我使用一个变量“互斥体”来让一个线程每次都递减,但是出错了。这里是我的代码:使用信号屏蔽java中的线程
public class Client extends Thread{
static int nbPlace=10;
static int mutex=1;
public Client(String name){
super(name);
}
public void run(){
if (mutex==1) {
mutex=0;
decrementer(getName());
mutex=1;
} else
try {
join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void decrementer(String nomThread){
nbPlace--; System.out.println("dec par "+nomThread+" ... nbplace="+nbPlace);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Client [] t= new Client[5];
for(int i=0;i<5;i++) t[i]=new Client ("thread n° "+i);
for (int i=0;i<5;i++) t[i].start();
}
}
为什么不只是让你的'递减'方法'同步'? –
“出了问题”你能更具体吗? –
有没有理由不使用AtomicInteger或CountdownLatch?或者是信号量。 –