Reputation: 2619
The following example is from a book explaining Race conditions. The example says that it has 2 threads. I can only see 1 thread implemented i.e. Thread lo = new Race0();
. Can someone please help me understand the program? I am new to multi-threading environment.
Where is the first thread being invoked?
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;
}
}
}
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++;
}
}
Upvotes: 2
Views: 95
Reputation: 393946
One thread is the main thread that the main
method is running in, and the other thread is the thread that it instantiates and starts (Thread lo = new Race0();
).
A java program starts with execuing the main
method in the main thread.
This program creates a second thread, lo
, starts the thread (by calling lo.start();
), and runs a loop.
At this point the main thread is running the loop :
while (!done) {
s.bump();
sleep(30);
}
At the same time, the second thread, lo
, is executing its run
method :
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;
}
Upvotes: 6