???博主介绍:大家好,我是,一名在校大学生,热爱分享知识,很高兴在这里认识大家??
??擅长领域:Java、大数据、运维、电子
???如果本文章各位小伙伴们有帮助的话,??关注+???点赞+??评论+??收藏,相应的有空了我也会回访,互助!!!
??另本人水平有限,旨在创作简单易懂的文章,在文章描述时如有错,恳请各位大佬指正,在此感谢!!!
文章目录
Volatile
-
保证可见性
package icu.lookyousmileface.volatilecode; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author starrysky * @title: VolatileUse * @projectName Juc_Pro * @description: volatile原子性测试 * @date 2021/1/307:52 上午 */ public class VolatileShow { /** * // 不加 volatile 程序就会死循环! * // 加 volatile 可以保证可见性 */ private volatile static int num = 0; public static void main(String[] args) { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 5, Runtime.getRuntime().availableProcessors(), 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy() ); //线程1对内存中num=1的变化不知道 threadPoolExecutor.execute(() -> { while (num == 0) { } }); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } num = 1; System.out.println("num:"+num); threadPoolExecutor.shutdown(); } }
-
不保证原子性
原子性 : 不可分割
线程A在执行任务的时候,不能被打扰的,也不能被分割。要么同时成功,要么同时失败。
/** * @author starrysky * @title: VolatileNotAtomic * @projectName Juc_Pro * @description: Volatile不保证原子性 * @date 2021/1/3011:32 上午 */ public class VolatileNotAtomic { private volatile static int num = 0; public static void add(){ num&