Updating a Common Value Across Multiple Threads - Java Thread

Java examples for Thread:atomic

Introduction

Use a DoubleAdder or LongAdder to ensure safe handling.

Demo Code

import java.util.concurrent.atomic.DoubleAdder;
import java.util.concurrent.atomic.LongAdder;

public class Main {
  public static void main(String[] args) {
    DoubleAdder da = new DoubleAdder();
    LongAdder la = new LongAdder();

    Thread thread1 = new Thread(() -> {
      for (int i1 = 0; i1 < 10; i1++) {
        da.add(i1);//from ww  w  .j  av a2 s .  c om
        la.add(i1);
        System.out.println("thread 1" + i1);
      }
    });

    Thread thread2 = new Thread(() -> {
      for (int i1 = 0; i1 < 10; i1++) {
        da.add(i1);
        la.add(i1);
        System.out.println("thread 2" + i1);
      }
    });

    thread1.start();
    thread2.start();

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("The sum is: " + da.doubleValue());
    System.out.println("The sum is: " + la.doubleValue());
  }
}

Result


Related Tutorials