Java Reference
In-Depth Information
}
}
};
Thread thdA = new Thread(r);
thdA.setName("A");
Thread thdB = new Thread(r);
thdB.setName("B");
thdA.start();
thdB.start();
}
}
Listing4-18 revealsthatThreadsAandBexecute Thread.sleep(100); tosleep
for100milliseconds.Thissleepresultsineachthreadexecutingmorefrequently,asthe
following partial output reveals:
A: 0
B: 0
A: 1
B: 1
A: 2
B: 2
A: 3
B: 3
A thread will occasionally start another thread to perform a lengthy calculation,
download a large file, or perform some other time-consuming activity. After finishing
itsothertasks,thethreadthatstartedtheworkerthreadisreadytoprocesstheresultsof
the worker thread and waits for the worker thread to finish and die.
Itispossibletowaitfortheworkerthreadtodiebyusingawhileloopthatrepeatedly
calls Thread 's isAlive() methodontheworkerthread's Thread objectandsleeps
for a certain length of time when this method returns true. However, Listing 4-19
demonstrates a less verbose alternative: the join() method.
Listing 4-19. Joining the default main thread with a background thread
class JoinDemo
{
public static void main(String[] args)
Search WWH ::




Custom Search