在我的课堂上,我的代码如下:
int counter1;
int counter2;
public void method1(){
if (counter1>0) {
...........do something
if (counter2>0) {
....do something else
}
}
public void method2() {
counter1=0;
counter2=0;
}
我需要将两个计数器放在一起.我担心只能在设置counter1后才能调用OS.有可能吗?
谢谢.
解决方法:
private int counter1;
private int counter2;
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock r = rwl.readLock();
private final Lock w = rwl.writeLock();
public void method1(){
r.lock();
try {
if (counter1>0) {
...........do something
if (counter2>0) {
....do something else
}
} finally { r.unlock(); }
}
public void method2() {
w.lock();
try {
counter1=0;
counter2=0;
} finally { w.unlock(); }
}
标签:java,atomic,multithreading,concurrency,operation
来源: https://codeday.me/bug/20190609/1208454.html