java volatile 过时_Java Volatile的一个实际应用场合

Consider the following example:

package thread;

public class ThreadVerify {

public static boolean stop = false;

public static void main(String args[]) throws InterruptedException {

Thread testThread = new Thread(){

@Override

public void run(){

int i = 1;

while(!stop){

//System.out.println("in thread: " + Thread.currentThread() + " i: " + i); i++;

}

System.out.println("Thread stop i="+ i);

}

};

testThread.start();

Thread.sleep(1000);

stop = true;

System.out.println("now, in main thread stop is: " + stop);

testThread.join();

}

}

The working thread is started to do increment on i and after one second, the flag is set as true in main thread. It is expected that we could see print out in working thread: “Thread stop i=”. Unfortunately it is NOT the case. Through process explorer we can find the working thread is still running:

The only way we can terminate it is to click this button in Eclipse:

The reason is: every thread in Java has its own thread local stack in runtime. Every time a thread tries to access the content of a variable, it first locates the variable content in the main memory, then loads this content from main memory to its local stack. Once this load is done, this relationship between thread local stack and main memory is cut.

Later, when thread performs modifications on the variable, the change is directly done on thread local stack. And at a given time ( scheduled by JVM, developer has no control about this timeslot), the change will be refreshed from thread local stack to memory. Back to our example, already the main thread has changed the flag to true in one second later ( this is TOO late! ), unfortunately when the working thread reads the flag from its own local stack, the flag is still false ( it makes sense since when it is copied from main memory in main thread ), so the working threads could never end. See the following picture for detail.

Solution is: add keyword volatile to flag variable, to force the read access on it in working thread is done always from main memory, so that after the flag is changed to true in main thread, later the working thread can detect this latest change since it reads data from main memory now. After this keyword is added we can get expected output:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
Java中,volatile关键字通常用于以下两个场景: 1. 多线程之间的变量可见性: 当多个线程共享一个变量时,使用volatile关键字可以确保当一个线程修改了该变量的值后,其他线程能够立即看到最新的值。这样可以避免使用过期的缓存值,从而保证线程之间的通信和协同工作。例如: ```java class SharedData { volatile int count = 0; } class MyThread extends Thread { private SharedData sharedData; public MyThread(SharedData sharedData) { this.sharedData = sharedData; } public void run() { sharedData.count++; } } public class Main { public static void main(String[] args) throws InterruptedException { SharedData sharedData = new SharedData(); MyThread[] threads = new MyThread[10]; for (int i = 0; i < 10; i++) { threads[i] = new MyThread(sharedData); threads[i].start(); } for (int i = 0; i < 10; i++) { threads[i].join(); } System.out.println(sharedData.count); // 输出的结果应为10 } } ``` 2. 状态标志位: 当一个变量用于标识某个状态时,使用volatile关键字可以确保不同线程之间对该状态的可见性,从而实现线程之间的协作。例如: ```java class MyThread extends Thread { private volatile boolean isRunning = true; public void stopRunning() { isRunning = false; } public void run() { while (isRunning) { // 执行任务逻辑 } } } public class Main { public static void main(String[] args) throws InterruptedException { MyThread thread = new MyThread(); thread.start(); Thread.sleep(1000); thread.stopRunning(); thread.join(); } } ``` 在上述例子中,当isRunning被设置为false时,线程会停止运行。由于isRunning是volatile变量,所以对isRunning的修改对其他线程是可见的,从而能够确保线程可以及时停止。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值