Last active
August 29, 2015 14:07
-
-
Save Korilakkuma/161a986c67db0c0efc9c to your computer and use it in GitHub Desktop.
CAS (Compare And Swap)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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