我一直在研究一些基本的多线程示例,并尝试实现一些代码以了解如何
线程优先级工作:
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
此输出使我非常困惑,因为:
我真的很感谢任何对此发生原因的解释,
谢谢。
最佳答案
您拥有线程优先级,并且一切顺利。唯一的问题是stop
不一定在所有线程上都具有相同的值。每个线程将自己的stop
值缓存在线程本地内存中。当一个线程将其stop
的值设置为true
时,其他线程不一定“看到”该更改。解决方法很简单;只需将stop
声明为volatile
即可,如下所示:
private static volatile boolean stop = false;
这会将变量保留在主内存中,因此强制线程彼此通信。
关于java - 多线程怪异行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62800992/