简体   繁体   English

使用volatile关键字的基本线程功能

[英]Basic thread functionality using volatile keyword

I need clarification related to basic thread functionality and volatile method.In the given example: 我需要澄清与基本线程功能和volatile方法有关的示例。

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;
       }
    }

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....:( 因此,这里的“ hi”对象是currentThread和在“ hi”内部创建的子线程共有的。这意味着它们都引用相同的内存位置。...在这种情况下,如果currentThread修改了变量“ running”的值(不使用volatile),则这意味着值已从子线程读取其值的位置更新到内存位置.....但是我想正在发生其他事情,并且我的概念尚不清楚,因为如果不使用volatile进入无限循环,请说明其发生情况内部.....我的意思是两个线程都指向同一个对象,volatile造成了什么区别。我真的很困惑.... :(

Basically what is happening is that the JVM normally allows threads to cache copies of instance or class variables ie each thread might have their own copy. 基本上发生的事情是,JVM通常允许线程缓存实例或类变量的副本,即每个线程可能都有自己的副本。 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 ,JVM将不允许线程缓存变量的副本,并且变量将保存在单个位置(主内存)中,因此,如果多个线程正在读取一个值,则它们将获得相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM