我只需要用java線程做一個競爭條件的例子,我編寫了這段代碼,但我不確定它是否有競爭條件。這段代碼是否有競爭狀態?
有人可以告訴我,如果下面的代碼有競爭條件,以及我怎樣才能改善或簡化?
(抱歉不好英語)
public class RaceCondition extends Thread{
static int count=0; //the variable where the race condition need to happen
static int contador1 = 0; //variables to count
static int contador2 = 0;
static Thread t1 = new Thread(new Runnable() {
public void run(){
while(contador1!=20){
count ++;
System.out.print(count + " ");
contador1++;
}
}
});
static Thread t2 = new Thread(new Runnable() {
public void run(){
while(contador2!=20){
int k = 5;
count += 5*k;
System.out.print(count + " ");
contador2 ++;
}
}
});
public static void main(String[] args) {
t1.start();
System.out.println(" ");
t2.start();
}
}
代碼必須運行纔能有競爭狀態。我沒有看到「count」的聲明。這段代碼是否編譯? – erickson
@user如果程序運行,線程將繼續運行直到它們完成,因爲它們不是守護進程線程。你在看什麼? – erickson
@user主線程在主線程完成後將死亡,線程不會。 –