您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java线程之Happens before规则是什么

2025/11/6 21:54:48发布24次查看
正文happens-before 规定了对共享变量的写操作对其它线程的读操作可见,它是可见性与有序性的一套规则总结,抛开以下 happens-before 规则,jmm 并不能保证一个线程对共享变量的写,对于其它线程对该共享变量的读可见.
案例1线程解锁 m 之前对变量的写,对于接下来对 m 加锁的其它线程对该变量的读可见
static int x; static object m = new object(); new thread(()->{ synchronized(m) { x = 10; } },"t1").start(); new thread(()->{ synchronized(m) { system.out.println(x); } },"t2").start();/*运行结果:10*/
案例2线程对 volatile 变量的写,对接下来其它线程对该变量的读可见
volatile static int x; new thread(()->{ x = 10; },"t1").start(); new thread(()->{ system.out.println(x); },"t2").start();/*运行结果:10*/
案例3线程 start 前对变量的写,对该线程开始后对该变量的读可见
static int x;x = 10;new thread(()->{ system.out.println(x);},"t2").start();/*运行结果:10*/
案例4线程结束前对变量的写,对其它线程得知它结束后的读可见(比如其它线程调用 t1.isalive() 或 t1.join()等待 它结束)
static int x;thread t1 = new thread(()->{ x = 10;},"t1");t1.start();t1.join();system.out.println(x);/*运行结果:10*/
案例5线程 t1 打断 t2(interrupt)前对变量的写,对于其他线程得知 t2 被打断后对变量的读可见(通过 t2.interrupted 或 t2.isinterrupted)
static int x;public static void main(string[] args) { thread t2 = new thread(()->{ while(true) { if(thread.currentthread().isinterrupted()) { system.out.println(x); break; } } },"t2"); t2.start(); new thread(()->{ sleep(1); x = 10; t2.interrupt(); },"t1").start(); while(!t2.isinterrupted()) { thread.yield(); } system.out.println(x);}/*运行结果:10*/
案例6对变量默认值(0,false,null)的写,对其它线程对该变量的读可见
static int a; public static void main(string[] args) { new thread(()->{ system.out.println(a); }).start(); }/*运行结果:0*/
案例7具有传递性,如果 x hb-> y 并且 y hb-> z 那么有 x hb-> z ,配合 volatile 的防指令重排,有下面的例子
volatile static int x;static int y;new thread(()->{ y = 10; x = 20;},"t1").start();new thread(()->{ // x=20 对 t2 可见, 同时 y=10 也对 t2 可见 system.out.println(x); },"t2").start();/*运行结果:20*/
以上就是java线程之happens before规则是什么的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product