代码在线链接: https://onlinegdb.com/rkdjD1eIr
代码:
class SomeThread extends Thread{
static volatile int count;
public void run(){
System.out.println("count value unsync"+count);
synchronized(SomeThread.class){
count = count + 1;
System.out.println("Thread number = "+ (count));
}
}
}
class Main{
public static void main(String args[]) throws Exception {
for(int i =0;i<20;i++){
SomeThread t = new SomeThread();
t.start();
//t.join();
for(int j=0;j<1000000;j++);
//t.sleep(100);
}
}
}
当我运行给定的程序时,我得到以下输出:
count value unsync0
count value unsync1
count value unsync1
Thread number = 1
Thread number = 2
Thread number = 3
count value unsync3
Thread number = 4
count value unsync4
Thread number = 5
count value unsync5
Thread number = 6
count value unsync6
Thread number = 7
count value unsync7
Thread number = 8
count value unsync8
Thread number = 9
count value unsync0
// How is the count value displayed as 0 when count was just set to 9
count value unsync0
Thread number = 10
count value unsync0
count value unsync10
count value unsync10
count value unsync10
count value unsync10
count value unsync10
Thread number = 11
count value unsync0
count value unsync0
Thread number = 12
Thread number = 13
Thread number = 14
count value unsync0
Thread number = 15
Thread number = 16
Thread number = 17
Thread number = 18
Thread number = 19
Thread number = 20
不同步部分的计数值如何减少? 我的理解是,每当线程有机会运行它时,就会显示计数值。 因此,如果线程 1 到来并增加 count 变量的值,则所有线程的 count 值都应为 1,因为我已将 count 变量描述为静态。所以count变量应该被每个线程共享。
因此,count 的值在任何时候都不应小于它在同步块(synchronized block)中设置的值。 意思是,如果计数值设置为1,则应该始终显示大于1或等于1的计数值。
预期输出为:count 的值绝不能小于之前显示的 count 值;
最佳答案
其中一个线程可能已经完成了句子(将 int 添加到字符串中),但由于某种原因,不得不等待一段时间。与此同时,其他线程正在输出各种值。当第一个缓慢的线程轮到输出句子时,它已经过时了。
关于java - 了解多线程 : Random Output in Unsynchronous Threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823981/