Skip to content

Commit e53df3d

Browse files
committed
Atomic variable usage demo.
1 parent d6136e7 commit e53df3d

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Chapter10/AtomicVariableDemo.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.concurrent.atomic.AtomicLong;
2+
import java.util.concurrent.ExecutorService;
3+
import java.util.concurrent.Executors;
4+
5+
public class AtomicVariableDemo{
6+
public static void main(String[] args){
7+
int threadAcount = 20;
8+
ExecutorService es = Executors.newFixedThreadPool(threadAcount);
9+
Runnable runnable = new Runnable(){
10+
public void run(){
11+
System.out.println(Thread.currentThread() + " get id: " + ID.getNextID());
12+
if(ID.getNextID() == threadAcount){
13+
es.shutdown();
14+
}
15+
}
16+
};
17+
for(int i=0; i<threadAcount; i++){
18+
es.submit(runnable);
19+
}
20+
}
21+
}
22+
23+
class ID{
24+
private static AtomicLong nextID = new AtomicLong(0);
25+
26+
static long getNextID(){
27+
return nextID.getAndIncrement();
28+
}
29+
}

0 commit comments

Comments
 (0)