zoukankan      html  css  js  c++  java
  • 【Java6学习笔记】多线程编程中使用volatile保障原子性

    作者:gnuhpc
    出处:http://www.cnblogs.com/gnuhpc/

    当多个线程使用同一个变量时,每个线程都在其本地缓冲中有一个这个变量的拷贝,对这个变量的改变实际上是对这个复制品进行改变。而另一个线程在使用这个变量时还可能一无所知。为了避免这个问题,使用volatile这个关键字对便变量进行修饰,在对变量进行改变时直接作用于主内存。
    package javabeat.samples;
    class ExampleThread extends Thread {
        private volatile int testValue;
        public ExampleThread(String str){
            super(str);
        }
        public void run() {
            for (int i = 0; i < 3; i++) {
                try {
                    System.out.println(getName() + " : "+i);
                    if (getName().equals("Thread 1 "))
                    {
                        testValue = 10;
                    }
                    if (getName().equals("Thread 2 "))
                    {
                        System.out.println( "Test Value : " + testValue);
                    }               
                    Thread.sleep(1000);
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }
            }
        }
    }
    public class VolatileExample {
        public static void main(String args[]) {
            new ExampleThread("Thread 1 ").start();
            new ExampleThread("Thread 2 ").start();
        }
    }

    作者:gnuhpc
    出处:http://www.cnblogs.com/gnuhpc/

  • 相关阅读:
    Advanced Developer's Blog
    图片文字识别
    Unit test resources
    SpringBoot-mvn插件
    flask中使用proto3
    QTA-qtaf自动化测试实践
    AttributeError: module 'virtualenv' has no attribute 'create_environment'
    qtaf dick 报错 NameError: name 'dict_values' is not defined
    24点python实现
    mysql在win下移植
  • 原文地址:https://www.cnblogs.com/gnuhpc/p/2822289.html
Copyright © 2011-2022 走看看