/* * * 原子性 * * 在32位的虚拟机中,Long的赋值不是原子性的,可能会出现以下输出: * 4294966852 -4294967185 4294966852 4294966852 4294966852 * * */ public class MultiThreadLong { static long t = 0; public static class ChangeT implements Runnable{ long to; public ChangeT(long to){ this.to = to; } @Override public void run() { while (true){ MultiThreadLong.t = to; Thread.yield(); } } } public static class ReadT implements Runnable{ @Override public void run() { while (true){ long t = MultiThreadLong.t; if(111L != t && -999L != t && 333L != t && -444L != t){ System.out.println(t); } Thread.yield(); } } } public static void main(String[] args) { new Thread(new ChangeT(111L)).start(); new Thread(new ChangeT(-999L)).start(); new Thread(new ChangeT(333L)).start(); new Thread(new ChangeT(-444L)).start(); new Thread(new ReadT()).start(); } }
Long 在多线程
最新推荐文章于 2022-04-18 23:37:42 发布