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/

  • 相关阅读:
    linux du命令
    Linux vmstat命令实战详解
    linux sar命令详解
    xargs 命令教程
    Linux中find命令用法大全
    python suprocess
    Python的f-strings格式化
    python glob的使用
    python getopt()的使用
    Java测试的题目感想
  • 原文地址:https://www.cnblogs.com/gnuhpc/p/2822289.html
Copyright © 2011-2022 走看看