gpt4 book ai didi

Java 多线程跳过循环并给出错误的结果

转载 作者:行者123 更新时间:2023-11-30 07:58:17 26 4
gpt4 key购买 nike

<分区>

Java 多线程跳过循环并给出错误结果

package Threading;

class DemoThread extends Thread{ //Thread Class
static int count=0; // variable incremented by both the threads

public DemoThread(String name) {
// TODO Auto-generated constructor stub
super(name);
}

public void run() {
for(int i=0;i<100000;i++) {
count++;
System.out.println(Thread.currentThread()+"Count"+count); // print thread operating on count variable
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


public class MyThreadClass {

public static void main(String[] args) {
// TODO Auto-generated method stub
DemoThread t1=new DemoThread("T1");
DemoThread t2=new DemoThread("T2");
t1.start();
t2.start();
try {
t1.join();
t2.join(); //allowing both the threads to complee before main thread
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("Main Thread ends"+DemoThread.count); //final value of count
}
}

count 的最终值应为 199998,但未给出所需的结果。为什么线程缺少循环???

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