AtomicInteger原子操作实现同步

package Thread.Common;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest implements Runnable {

    private AtomicInteger i = new AtomicInteger(0);

    public int getValue() {
        return i.get();
    }

    private void evenIncrement() {
        i.addAndGet(2);
    }

    @Override
    public void run() {
        while (true) {
            evenIncrement();
        }
    }

    public static void main(String[] args) {
     //定时执行任务
new Timer().schedule(new TimerTask() { @Override public void run() { System.err.println("Aborting"); System.exit(0); } }, 5000); ExecutorService exec = Executors.newCachedThreadPool(); AtomicIntegerTest ait = new AtomicIntegerTest(); exec.execute(ait); while (true) { int val = ait.getValue(); if (val % 2 != 0) { System.out.println(val); System.exit(0); } } } }

 

相关文章:

  • 2021-10-11
  • 2022-12-23
  • 2021-10-06
  • 2021-11-29
  • 2021-09-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-03
  • 2021-10-20
  • 2021-08-10
  • 2021-08-01
相关资源
相似解决方案