Ray AtomicInteger atomic increment type

AtomicInteger atomic operation type:

 

private static Integer num = 0; 19055 results obtained for num ++

 

private static volatile Integer num = 0; 19550 results obtained for num ++

 

At this time, the introduction of java classes AtomicInteger under contract and, with its high atomic operation concurrency problem solving:

public class MyAtomicInteger { private static final Integer threadCount = 20;

private static AtomicInteger count = new AtomicInteger(0); private static void increase() { count.incrementAndGet(); }

public static void main(String[] args) { Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(() -> { for (int i1 = 0; i1 < 1000; i1++) { increase(); } }); threads[i].start(); }

while (Thread.activeCount() > 1) {

// call the yield method means that the current thread will hand over authority CPU, so CPU to perform other threads. It is similar with sleep method, the same will not release the lock. // But the yield can not hand over control of specific CPU time, in addition, the method can only yield so that the thread has the same priority a chance to get the execution time of the CPU. // Note that calling yield method does not make the thread into the blocked state, but to let the thread back to the ready state, it only needs to wait to reacquire CPU execution time, and this is not the same methods and sleep Thread.yield (); } System.out.println (. Thread.currentThread () getName ()); System.out.println ( "NUM:" + COUNT); } }

result:

main

a: 40000

Guess you like

Origin www.cnblogs.com/tian-Bao555/p/12128433.html