的Java多線程跳過循環,並給出錯誤的結果的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
}
}
計數的最終值應該是199998,但它沒有給出期望的結果。 爲什麼線程缺少循環?
格式的代碼,請。 –