Java Reference
In-Depth Information
This approach is, however, not recommended because it mixes the task and the mecha-
nism of running the task. Separating the task from the thread is a preferred design.
Note
The Thread class also contains the stop() , suspend() , and resume() methods.
As of Java 2, these methods were deprecated (or outdated ) because they are known to
be inherently unsafe. Instead of using the stop() method, you should assign null to
a Thread variable to indicate that has stopped.
deprecated method
You can use the yield() method to temporarily release time for other threads. For exam-
ple, suppose you modify the code in the run() method in lines 53-57 for PrintNum in
Listing 30.1 as follows:
yield()
public void run() {
for ( int i = 1 ; i <= lastNum; i++) {
System.out.print( " " + i);
Thread.yield();
}
}
Every time a number is printed, the thread of the print100 task is yielded to other threads.
The sleep(long millis) method puts the thread to sleep for a specified time in
milliseconds to allow other threads to execute. For example, suppose you modify the code in
linesĀ 53-57 in Listing 30.1, as follows:
sleep(long)
public void run() {
try {
for ( int i = 1 ; i <= lastNum; i++) {
System.out.print( " " + i);
if (i >= 50 ) Thread.sleep( 1 );
}
}
catch (InterruptedException ex) {
}
}
Every time a number ( >= 50 ) is printed, the thread of the print100 task is put to sleep for
1 millisecond.
The sleep method may throw an InterruptedException , which is a checked exception.
Such an exception may occur when a sleeping thread's interrupt() method is called. The
interrupt() method is very rarely invoked on a thread, so an InterruptedException
is unlikely to occur. But since Java forces you to catch checked exceptions, you have to put
it in a try-catch block. If a sleep method is invoked in a loop, you should wrap the loop
in a try-catch block, as shown in (a) below. If the loop is outside the try-catch block, as
shown in (b), the thread may continue to execute even though it is being interrupted.
InterruptedException
public void run() {
try {
while (...) {
...
Thread.sleep( 1000 );
public void run() {
while (...) {
try {
...
Thread.sleep(sleepTime);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
(b) Incorrect
(a) correct
 
 
Search WWH ::




Custom Search