Skip to content

Instantly share code, notes, and snippets.

@Korilakkuma
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save Korilakkuma/161a986c67db0c0efc9c to your computer and use it in GitHub Desktop.

Select an option

Save Korilakkuma/161a986c67db0c0efc9c to your computer and use it in GitHub Desktop.
CAS (Compare And Swap)
import java.util.concurrent.atomic.*;
public final class AtomicThread {
private static final int NUM_LOAD = 100000;
private AtomicInteger count = new AtomicInteger();
private static class Worker implements Runnable {
private AtomicThread counter = null;
public Worker(AtomicThread counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < AtomicThread.NUM_LOAD; i++) {
this.counter.count.getAndIncrement();
}
}
}
public AtomicThread() {
}
public AtomicInteger getCount() {
return this.count;
}
public static void main(String[] args) throws InterruptedException {
AtomicThread counter = new AtomicThread();
Thread thread1 = new Thread(new Worker(counter));
Thread thread2 = new Thread(new Worker(counter));
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(counter.getCount());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment