Last active
September 11, 2015 11:28
-
-
Save glebmtb/0be11ffbd7403b7f680c to your computer and use it in GitHub Desktop.
Hello World Atomic
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
package cun; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class TestCounter { | |
public static void main(String[] args) { | |
ExecutorService executors = Executors.newCachedThreadPool(); | |
Counter counter = new Counter(); | |
executors.submit(new TestThread(counter, "thread1")); | |
executors.submit(new TestThread(counter, "thread2")); | |
executors.submit(new TestThread(counter, "thread3")); | |
executors.submit(new TestThread(counter, "thread4")); | |
executors.submit(new TestThread(counter, "thread5")); | |
} | |
static class TestThread implements Runnable { | |
Counter counter; | |
String name; | |
public TestThread(Counter counter, String name) { | |
this.counter = counter; | |
this.name = name; | |
} | |
@Override | |
public void run() { | |
for (int i = 1; i < 3; i++) { | |
System.out.println(name + ": " + counter.increment()); | |
} | |
} | |
} | |
static class Counter { | |
AtomicInteger i = new AtomicInteger(); | |
int increment() { | |
int old; | |
int newResult; | |
do { | |
old = i.get(); | |
try { | |
Thread.sleep(1); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
newResult = old + 1; | |
} | |
while (!i.compareAndSet(old, newResult)); | |
return newResult; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output
thread2: 1
thread1: 2
thread1: 3
thread4: 4
thread2: 5
thread4: 6
thread3: 7
thread3: 8
thread5: 9
thread5: 10