计数器变量并不能准确反射(reflect)增量的次数 方法被调用。为什么不,如何解决? (你不必写代码, 只用英语。)
原文:
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();
}
}
由于您首先获取
,因此您还需要至少 1 个许可,否则没有什么可获取
:
static Semaphore lock = new Semaphore(1);
synchronized
block 比 Semaphore
更容易:
while (true) {
synchronized (Foopadoop.class) {
counter++;
}
}
或一个 AtomicInteger:
static AtomicInteger counter = new AtomicInteger();
// ...
while (true) {
counter.getAndIncrement();
}
关于Java多线程信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430544/