using Atomboolean to implement atomic operations
Packageatomactions;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.atomic.AtomicBoolean;/*** Created by Xfyou 2018/6/20 16:29.*/ Public classBarworkerImplementsRunnable {/*** <p> * Atomicboolean is an atomic variable under the Java.util.concurrent.atomic package, which provides a set of atomic classes. * <p> * Its basic feature is that in a multithreaded environment, when there are multiple threads executing the methods contained in the instances of these classes, there is exclusivity, that is, when a thread enters the method and executes the instruction, it is not interrupted by another thread, and the other thread is like a spin lock until the method executes. , it is only a logical understanding that the JVM chooses a second thread from the waiting queue to enter. * <p> * is actually implemented with hardware-related directives that do not block threads (or simply block at the hardware level). * <p> * For example Atomicboolean, when this boolean value is changed, it is not allowed to be inserted between, maintaining the atomicity of the operation. Methods and Examples: Compareandset (Boolean expect, Boolean update). * This method mainly two functions * 1. Compare the values of Atomicboolean and expect, and if consistent, execute the statements within the method. is actually an if statement * 2. Setting the value of the Atomicboolean to update the most thing is that the two things are one go, this will not be interrupted between the actions, any internal or external statements will not be able to run between two actions. Provides a solution for multi-threaded control. */ Private StaticAtomicboolean exist =NewAtomicboolean (false); @Override Public voidrun () {String name=Thread.CurrentThread (). GetName (); if(Exist.compareandset (false,true) {System.out.println (name+ "Enter"); Try{System.out.println (name+ "Working"); TimeUnit.SECONDS.sleep (2); } Catch(interruptedexception e) {// do nothing} System.out.println (name+ "Leave"); Exist.set (false); } Else{System.out.println (name+ "Give up"); } } /*** Only one thread is working, because Exists.compareandset (false, True) provides atomic operations, and the comparison and assignment operations make up an atomic operation * *@paramargs args*/ Public Static voidMain (string[] args) {Barworker bw=NewBarworker (); Executorservice Executorservice= Executors.newfixedthreadpool (5); for(inti = 0; I < 5; i++) Executorservice.execute (BW); Executorservice.shutdown (); }}
One of the possible output results is:
Pool-1-thread-1 enterpool-1-thread-1 workingpool-1-thread-3 give uppool-1-thread-4 give uppool-1-thread-5 give Uppool-1-thread-2 giveup pool-1-thread-1 leave
Java Atomicboolean (Java code Combat-008)