zoukankan      html  css  js  c++  java
  • 2.3.2解决同步死循环

    测试如下

    package com.cky.test;
    
    /**
     * Created by edison on 2017/12/9.
     */
    public class PrintString implements  Runnable{
        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();
                }
            }
        }
    
        @Override
        public void run() {
            printStringMethod();
        }
    }
    package com.cky.test;
    
    /**
     * Created by edison on 2017/12/9.
     */
    public class Run {
        public static void main(String[] args) {
    
            PrintString printString = new PrintString();
            new Thread(printString).start();
            System.out.println("我要停止他 stop"+ Thread.currentThread().getName());
            printString.setContinuePrint(false);
    
        }
    }
    我要停止他 stopmain
    run printThread-0

    但当上面的例子代码的格式运行在-server服务器的模式中64bit的JVM上时,会出现死循环

    解决的方案时使用volatile关键字

    关键字volatile的作用是强制从公共堆栈中取得变量的值,而不是从线程私有数据栈中取得变量的值

  • 相关阅读:
    2015-3-27
    2015-3-26
    2015-3-25
    2015-3-24
    oracle数据字典表 系统表
    PowerDesigner教程系列(六)概念数据模型
    PowerDesigner教程系列(五)概念数据模型
    PowerDesigner教程系列(四)概念数据模型
    PowerDesigner教程系列(三)概念数据模型
    PowerDesigner教程系列(二)概念数据模型
  • 原文地址:https://www.cnblogs.com/edison20161121/p/8011204.html
Copyright © 2011-2022 走看看