关键字volatile的主要作用是使变量在多个线程间可见。
测试如下
package com.cky.test; /** * Created by edison on 2017/12/9. */ public class PrintString { private boolean isContinuePrint = true; public boolean getContinuePrint() { return isContinuePrint; } public void setContinuePrint (boolean isContinuePrint) { this.isContinuePrint = isContinuePrint; } public void printStringMethod() { while(isContinuePrint) { try { System.out.println("run print"+Thread.currentThread().getName()); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.cky.test; /** * Created by edison on 2017/12/9. */ public class Run { public static void main(String[] args) { PrintString printString = new PrintString(); printString.printStringMethod(); System.out.println("我要停止他 stop"+ Thread.currentThread().getName()); printString.setContinuePrint(false); } }
run printmain run printmain run printmain run printmain
程序开始运行后
根本没停下来。原因是main线程一直处理while()循环,导致程序不能执行下面的代码。解决办法肯定是用多线程技术
时间: 2024-10-19 20:26:57