使用volatile关键字的基本线程功能 [英] Basic thread functionality using volatile keyword

查看:102
本文介绍了使用volatile关键字的基本线程功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要澄清有关基本线程功能和易失方法的信息.在给定的示例中:

I need clarification related to basic thread functionality and volatile method.In the given example:

public class ThreadDemo {
     public static void main(String args[]){
         Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         Priority_test hi=new Priority_test(Thread.NORM_PRIORITY+2);

         hi.start();

         try{
             Thread.sleep(1000);
         }catch(InterruptedException e){
             System.out.println("Main thread interrupted");
         }

         hi.stop();

         try{
             hi.t.join();
         }catch(InterruptedException e){
             System.out.println("Interrupted");
         }
         System.out.println("High priority:"+hi.click);
      } 
}

    public class Priority_test implements Runnable{
       Thread t; 
       long click=0;
       private volatile boolean running=true;
       Priority_test(int p){
           t=new Thread(this);
           t.setPriority(p);
       }

       public void run(){
           while(running)
               click++;
       }

       public void start(){
           t.start();
       }

       public void stop(){
         running=false;
       }
    }

因此,这里的'hi'对象是currentThread和在'hi'中创建的子线程共有的.这意味着它们都引用相同的内存位置....在这种情况下,如果currentThread修改了变量'running'的值(不使用易失性),则意味着值已更新到子线程正在读取其值的内存位置......但我猜想正在发生其他事情,我的概念还不清楚,因为不使用volatile会进入无限循环.请解释它是如何在内部发生的.....我的意思是两个线程都指向同一个对象,volatile造成了什么区别.我真的很困惑....:(

So,here 'hi' object is common to currentThread and child thread created inside 'hi'.That means both refer to same memory location....in that case if currentThread modifies value of variable 'running'(without using volatile) then it means value gets updated to the memory location from where child thread is reading its value.....but i guess something else is happening and my concept is not clear as without using volatile its going into infinite loop.Please explain how its happening internally.....i mean both threads are referring to same object and what difference does volatile make.I am really getting confused....:(

推荐答案

基本上,发生的事情是JVM通常允许线程缓存实例或类变量的副本,即每个线程可能都有自己的副本.如果一个线程更新了一个副本,则另一个线程可能看不到新值.通过使变量 volatile ,JVM将不允许线程缓存变量的副本,并且变量被保存在单个位置(主内存)中,因此,如果多个线程正在读取一个值,它们将得到结果相同.

Basically what is happening is that the JVM normally allows threads to cache copies of instance or class variables i.e. each thread might have their own copy. If one copy is updated by one thread, the other thread might not see the new value. By making a variable volatile, the JVM will not allow threads to cache copies of the variable and the variable is kept in a single location (main memory), so if multiple threads are reading a value they will get the same result.

这篇关于使用volatile关键字的基本线程功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆