【发布时间】:2015-10-05 21:40:00
【问题描述】:
我的目标是让多个线程同时访问一个静态属性“nbPlace”,并减少它。我使用变量“mutex”让一个线程每次递减,但是出了点问题。这是我的代码:
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();
}
}
【问题讨论】:
-
为什么不把你的
decrementer方法设为synchronized? -
“出了点问题”你能说得更具体点吗?
-
是否有充分的理由不使用 AtomicInteger 或 CountdownLatch?或者信号量,就此而言。
-
我期待所有线程减量 "nbPlace" ,但只有第一个做到了。
-
如果你让它变得易变有帮助吗? (还有互斥锁)
标签: java multithreading synchronization