Java thread Atomic class-related Operations Demo sample
Package Org.rui.thread.volatiles;import Java.util.timer;import Java.util.timertask;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.atomic.atomicinteger;/** * Atomic class. * Java SE5 introduces special atomic variable classes such as Atomicinteger atomiclong atomicreference *. They provide an atomic conditional update operation in the following form: * * Boolean compareandset (Expectedvalue,updatevalue); * * These classes are tuned to be available on some modern processors and are atomic at the machine level. * So when using them. There is usually no need to worry. They are rarely useful for routine programming, but when it comes to performance tuning, * they can be useful. For example, we can use Atomicinteger to rewrite Atomictytest.java * @author Lenovo * */public class Atomicintegertest implements Runnable {/** * Here we eliminate the Synchronizedkeyword by using Atomicinteger. * Because this program does not fail. So a timer was added so that after 5 seconds, he would voluntarily terminate */private Atomicinteger i=new atomicinteger (0);p ublic int GetValue () {return i.get ();} private void Evenincrement () {i.addandget (2);} @Overridepublic void Run () {while (true) {evenincrement ()}} public static void Main (string[] args) {//Order timer new Timer (). Schedule (new TimerTask () {@Overridepublic void run () {System.err . PRintln ("aborting"); System.exit (0);}, 5000);//thread pool Executorservice exec=executors.newcachedthreadpool (); Atomicintegertest at=new atomicintegertest (); Exec.execute (at), while (true) {int val=at.getvalue (); if (val%2!=0) { System.out.println (Val); System.exit (0);}}} /** * Output: * aborting */
Package Org.rui.thread.volatiles;import Java.util.concurrent.atomic.atomicinteger;import Org.rui.thread.res.evenchecker;import org.rui.thread.res.intgenerator;/** * The following is a rewrite of Mutexevengenerator.java with Atomicinteger: * All other forms of synchronization are eliminated by using Atomicinteger again * * * * It should be emphasized that The atomic class is designed to build classes in java.util.concureent. * It is therefore only possible to use them in your own code in exceptional circumstances, even if used, to ensure that there are no other problems that may arise.* Usually depending on the lock to be more secure (either Synchronizedkeyword, or an explicit lock object) * @author Lenovo * */public class Atomicevengenerator extends Intgenerator{private atomicinteger currentevenvalue=new atomicinteger (0); @Overridepublic int Next () {return Currentevenvalue.addandget (2);} public static void Main (string[] args) {evenchecker.test (New Atomicevengenerator ());}}
Java thread Atomic class-related Operations Demo sample thinking in Java4 folder 21.3.4