java - 多线程怪异行为

标签 java multithreading

我一直在研究一些基本的多线程示例,并尝试实现一些代码以了解如何
线程优先级工作:

class PriorityThreading extends Thread {

private static boolean stop = false;
private int count = 0;

public PriorityThreading(String name) { 
    super(name);
}

public void run() {
    do {
        count++;
    }while(stop==false && count<10000000 );
    stop = true;
}

public static void main (String [] args) throws InterruptedException{
    PriorityThreading thread = new PriorityThreading("thread 1");
    PriorityThreading thread2 = new PriorityThreading("thread 2");
    PriorityThreading thread3 = new PriorityThreading("thread 3");
    
    
    thread.setPriority(MAX_PRIORITY);
    thread2.setPriority(NORM_PRIORITY);
    thread3.setPriority(MIN_PRIORITY);
    
    thread.start();
    thread2.start();
    thread3.start();
    
    thread.join();
    thread2.join();
    thread3.join();
    
    
    System.out.println(thread.getName() + " " + thread.count);
    System.out.println(thread2.getName() + " " + thread2.count);
    System.out.println(thread3.getName() + " " + thread3.count);
    
}
}
我不断得到以下输出:
线程1 10000000
线程2 10000000
线程3 10000000
此输出使我非常困惑,因为:
  • 我希望只有一个线程达到总数,因为在第一个线程完成后必须停止while循环,并且stop = true
  • 其次,我希望只有优先级最高的线程1才能达到最大总数。

  • 我真的很感谢任何对此发生原因的解释,
    谢谢。

    最佳答案

    您拥有线程优先级,并且一切顺利。唯一的问题是stop不一定在所有线程上都具有相同的值。每个线程将自己的stop值缓存在线程本地内存中。当一个线程将其stop的值设置为true时,其他线程不一定“看到”该更改。解决方法很简单;只需将stop声明为volatile即可,如下所示:

    private static volatile boolean stop = false;
    
    这会将变量保留在主内存中,因此强制线程彼此通信。

    关于java - 多线程怪异行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62800992/

    相关文章:

    java - R Shiny DesktopDeployR 停止日志记录错误

    java - JMock 通用返回类型

    java - 如何使用锁来确保一个方法只能同时运行一定次数

    java - 0 超时的 future.get 行为

    c# - 回避异常和 "a function evaluation has timed out"

    java - 带有 $in 运算符的 mongodb find() 是顺序的还是并行的?

    java - 在 getRuntime().exec 中使用引号

    java - Android 的 StrictMode - 如何正确使用它,为什么没有它我的应用程序无法运行?

    c - 在 GTK 中使用多线程?

    java - 如何增加 hadoop 中 map 任务的数量以及如何获取 hadoop mapreduce 作业所花费的总时间