fsc*_*ore 2 java multithreading race-condition
以下示例来自一本解释竞争条件的书.该示例表明它有2个线程.我只能看到1个线程实现ie Thread lo = new Race0();.有人可以帮我理解这个程序吗?我是多线程环境的新手.
第一个被调用的线程在哪里?
Race0:
class Race0 extends Thread {
static Shared0 s;
static volatile boolean done = false;
public static void main(String[] x) {
Thread lo = new Race0();
s = new Shared0();
try {
lo.start();
while (!done) {
s.bump();
sleep(30);
}
lo.join();
} catch (InterruptedException e) {
return;
}
}
public void run() {
int i;
try {
for (i = 0; i < 1000; i++) {
if (i % 60 == 0)
System.out.println();
System.out.print(“.X”.charAt(s.dif()));
sleep(20);
}
System.out.println();
done = true;
} catch (InterruptedException e) {
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Shared0:
class Shared0 {
protected int x = 0, y = 0;
public int dif() {
return x - y;
}
public void bump() throws InterruptedException {
x++;
Thread.sleep(9);
y++;
}
}
Run Code Online (Sandbox Code Playgroud)
一个线程是main运行该方法的主线程,另一个线程是它实例化并启动的线程(Thread lo = new Race0();).
java程序首先main在主线程中执行该方法.
该程序创建第二个线程,lo启动线程(通过调用lo.start();),并运行循环.
此时主线程正在运行循环:
while (!done) {
s.bump();
sleep(30);
}
Run Code Online (Sandbox Code Playgroud)
同时,第二个线程lo正在执行其run方法:
try {
for (i = 0; i < 1000; i++) {
if (i % 60 == 0)
System.out.println();
System.out.print(“.X”.charAt(s.dif()));
sleep(20);
}
System.out.println();
done = true;
} catch (InterruptedException e) {
return;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |