【发布时间】:2016-01-22 20:10:59
【问题描述】:
我只需要用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的声明。这段代码能编译吗? -
@user 如果程序运行,线程将继续运行直到它们完成,因为它们不是守护线程。你在看什么?
-
@user 主线程在主线程完成后会死掉,活线程不会。
标签: java multithreading static java-threads