简体   繁体   English

如何在java中提供原子读/写2个变量?

[英]How provide in java atomic read/write of 2 variables together?

In my class I have code like: 在我的课堂上,我的代码如下:

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;
}

I need that both counters set together. 我需要将两个计数器放在一起。 I am afraid that OS can to method1 can be invoked after setting counter1 only. 我担心只能在设置counter1后才能调用OS。 Does it possible? 有可能吗? Thanks. 谢谢。

Either use the synchronized keyword as the other answer suggest or use the ReentrantReadWriteLock if you have more reads than writes to the counter, for better performance. 如果您有更多读取而不是写入计数器,请使用synchronized关键字作为另一个答案建议使用或使用ReentrantReadWriteLock,以获得更好的性能。 You can read about the lock here http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html 你可以在这里阅读有关锁的信息http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html

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(); }

}

Sure, just use the synchronized keyword: 当然,只需使用synchronized关键字:

private final Object LOCK = new Object();
int counter1;
int counter2;

public void method1() {
  synchronized(LOCK) {
     if (counter1>0) {
      ...........do something
       if (counter2>0) {
        ....do something else
       }
    }
}
public void method2() {
  synchronized(LOCK) {
    counter1=0;
    counter2=0;
  }
}

Some tips: 一些技巧:

Use a private object for synchronization rather than marking a method synchronized. 使用私有对象进行同步,而不是将方法标记为已同步。 This prevents something external to you class from grabbing the lock and stalling things. 这可以防止你上课以外的东西抓住锁并拖延东西。

Make sure that you use the synchronized keyword everywhere , and make sure you always synchronize on the same object. 确保在任何地方都使用synchronized关键字,并确保始终在同一对象上进行同步。 If you forget to do either of those things, two processes can access the fields at the same time. 如果您忘记执行其中任何一项操作,则两个进程可以同时访问这些字段。

Beware of deadlocks. 小心死锁。 In a perfect world you'd write unit tests to ensure that locking is working the way you think it is. 在完美的世界中,您需要编写单元测试,以确保锁定按您认为的方式工作。

使用synchronized块或方法来包装对两个计数器的访问,记住使用相同的对象来锁定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM