[英]Java Multi threading semaphore
counter 变量不能准确反映调用 increment 方法的次数。 为什么不可以,如何修复? (您不必编写代码,只需使用英文即可。)
原文:
import java.util.*;
import java.lang.*;
import java.io.*;
class Foopadoop
{
public static int counter = 0;
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
public void run() {
while(true){
counter++;
}
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
我的,我添加了一个信号量,但我不确定我做得对还是我想使用锁。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.Semaphore;
class Foopadoop
{
public static int counter = 0;
Semaphore lock = new Semaphore(0);
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
try{public void run() {
while(true){
counter++;
lock.acquire();
}
}
}finally{
lock.release();
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
这不是您使用Semaphore
。
您在访问共享资源之前获取它,并在之后释放它:
while (true) {
try {
lock.acquire();
counter++;
} finally {
lock.release();
}
}
由于您首先acquire
,因此您还需要至少 1 个许可证,否则没有什么可acquire
:
static Semaphore lock = new Semaphore(1);
synchronized
块比Semaphore
更容易:
while (true) {
synchronized (Foopadoop.class) {
counter++;
}
}
或 AtomicInteger:
static AtomicInteger counter = new AtomicInteger();
// ...
while (true) {
counter.getAndIncrement();
}
您也可以在 while 循环中添加 Thread.sleep(ms) ,以便它会暂停当前线程一段时间,并开始执行其他线程。 否则当前线程可能以自私的方式运行(自私线程)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.