Skip to content

Instantly share code, notes, and snippets.

@glebmtb
Last active September 11, 2015 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glebmtb/0be11ffbd7403b7f680c to your computer and use it in GitHub Desktop.
Save glebmtb/0be11ffbd7403b7f680c to your computer and use it in GitHub Desktop.
Hello World Atomic
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;
}
}
}
@glebmtb
Copy link
Author

glebmtb commented Sep 11, 2015

output
thread2: 1
thread1: 2
thread1: 3
thread4: 4
thread2: 5
thread4: 6
thread3: 7
thread3: 8
thread5: 9
thread5: 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment