gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:30:39 28 4
gpt4 key购买 nike

我需要与基本线程功能和 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;
}
}

因此,这里“hi”对象对于 currentThread 和在“hi”内创建的子线程是通用的。这意味着两者都引用相同的内存位置......在这种情况下,如果 currentThread 修改变量“running”的值(不使用 volatile )那么这意味着值被更新到子线程读取其值的内存位置......但我猜正在发生其他事情,并且我的概念不清楚,因为不使用 volatile 它会进入无限循环。请解释它是如何在内部发生的......我的意思是两个线程都引用同一个对象,并且 volatile 有什么区别。我真的很困惑......:(

最佳答案

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

关于java - 使用 volatile 关键字的基本线程功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30422755/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com