Java Reference
In-Depth Information
class named ReadAFile whose run method scans the contents of a fi le and prints them to
the console output:
import java.io.*;
import java.util.Scanner;
public class ReadAFile extends Thread {
private Scanner in;
private boolean keepGoing = true;
public ReadAFile(File f) throws FileNotFoundException {
in = new Scanner(f);
}
public void stopReading() {
keepGoing = false;
}
public void run() {
while(keepGoing && in.hasNext()) {
System.out.print(in.next());
}
}
}
The following statements instantiate a ReadAFile object and then wrap that object into
a new thread:
File source = new File(“somedata.txt”);
ReadAFile target = new ReadAFile(source);
Thread t = new Thread(target);
At this point in the program, t points to a new Thread object but the JVM has not
created a new thread in the process yet. Only when the start method is invoked on
the Thread does the JVM add a new thread to the process, at which point a new thread
transitions into a runnable thread , as Figure 5.1 shows.
FIGURE 5.1
A new thread transitions to a runnable thread when its start method is
invoked.
NEW
RUNNABLE
start()
Search WWH ::




Custom Search