Atomic operations in java multithreading

Perhaps atomic operations are not often used, but after all, they belong to the multi-threading chapter, so they are well documented.

package atomic operation;

import java.util.concurrent.atomic.AtomicInteger;
/*
 * The following two operations will always show different values ​​if you try several times
 * This is because the first operation is not thread-safe, and there will be cases where multiple threads operate on a value at the same time
 * The latter is the indivisible nature of atomic operations, so that will not happen
 * */
public class TestMyAtomic {
	static int index = 0;
	static int num = 10000;
						
	static AtomicInteger atomicIndex = new AtomicInteger(0); //Set the initial value to 0
	public static void main(String[] args) {
		// case one
		//The normal index++ operation is a non-atomic operation
		//Create 10,000 threads for index++ operation
		Thread[]  threads = new Thread[num];
		
		for (int i = 0; i < num; i++) {
			Thread t = new Thread() {
				@Override
				public void run() {
					index++;
				}
			};
			t.start();
			threads[i] = t;
		}
		
		for (Thread t : threads) {
			try {
				//Ensure that the current t thread joins the main thread, and then continue the operation after it finishes running
				t.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
		System.out.println(index);
		
		//case 2
		// The following are atomic operations
		Thread[]  threadsAtomic = new Thread[num];
		
		for (int i = 0; i < num; i++) {
			Thread t = new Thread() {
				@Override
				public void run() {
					atomicIndex.incrementAndGet();
				}
			};
			t.start();
			threadsAtomic[i] = t;
		}
		
		for (Thread t : threadsAtomic) {
			try {
				//Ensure that the current t thread joins the main thread, and then continue the operation after it finishes running
				t.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
		System.out.println(atomicIndex.intValue());
		
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325522411&siteId=291194637