Java multithreading --volatile

Volatile does not provide a locking mechanism, but only guarantees the visibility of the modification to other threads. When only one thread modifies the variable value, volatile can be used when multiple threads read the variable value. When multiple threads modify the variable value, there is no guarantee The safety of variables, the phenomenon of lost updates will occur.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test {
	volatile static int m = 0;

	public static void main(String[] args) throws InterruptedException {
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int j = 0; j < 10; j++) {
			exec.execute(new Runnable() {
				int count = 1000;

				@Override
				public void run() {
					while (count-- > 0)
							m++;
				}

			});
		}
		exec.shutdown();
		while (Thread.activeCount() > 1) {
			Thread.yield();
		}
		System.out.println(m);
	}
}

 

Guess you like

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