Class AtomicInteger java.lang.Object extended by java.lang.Number extended by java.util.concurrent.atomic.AtomicInteger All Implemented Interfaces: Serializable public class AtomicInteger extends Number implements Serializable
Anint
value that may be updated atomically. AnAtomicInteger
is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
lhp@nereida:~/Lgroovy/threads$ cat -n threads1.groovy 1 import java.util.concurrent.atomic.AtomicInteger 2 3 def counter = new AtomicInteger() 4 5 synchronized out(message) { 6 println(message) 7 } 8 9 def th = Thread.start { 10 for( i in 1..8 ) { 11 sleep 30 12 out "thread loop $i" 13 counter.incrementAndGet() 14 } 15 } 16 17 for( j in 1..4 ) { 18 sleep 50 19 out "main loop $j" 20 counter.incrementAndGet() 21 } 22 23 th.join() 24 25 assert counter.get() == 12
lhp@nereida:~/Lgroovy/threads$ lhp@nereida:~/Lgroovy/threads$ lhp@nereida:~/Lgroovy/threads$ groovy threads1.groovy thread loop 1 main loop 1 thread loop 2 main loop 2 thread loop 3 thread loop 4 main loop 3 thread loop 5 main loop 4 thread loop 6 thread loop 7 thread loop 8 |
lhp@nereida:~/Lgroovy/threads$ scp threads1.groovy etsii: threads1.groovy 100% 400 0.4KB/s 00:00 lhp@nereida:~/Lgroovy/threads$ ssh etsii 'groovy threads1.groovy' thread loop 1 main loop 1 thread loop 2 main loop 2 thread loop 3 thread loop 4 main loop 3 thread loop 5 thread loop 6 main loop 4 thread loop 7 thread loop 8 |
The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements.
To make a method synchronized, simply add the synchronized
keyword to its declaration.
Casiano Rodríguez León