Java基础之线程——使用Runnable接口(JumbleNames)

时间:2023-03-08 20:49:38
Java基础之线程——使用Runnable接口(JumbleNames)

控制台程序。

除了定义Thread新的子类外,还可以在类中实现Runnable接口。您会发现这比从Thread类派生子类更方便,因为在实现Runnable接口时可以从不是Thread的类派生子类,并且仍然表示线程。Java只允许有单个基类,如果类派生于Thread,就不能再继承其他类中的功能。Runnabel接口只定义了方法run(),这个方法在启动线程时执行。

 import java.io.IOException;

 public class JumbleNames implements Runnable {
// Constructor
public JumbleNames(String firstName, String secondName, long delay) {
this.firstName = firstName; // Store the first name
this.secondName = secondName; // Store the second name
aWhile = delay; // Store the delay
} // Method where thread execution will start
public void run() {
try {
while(true) { // Loop indefinitely...
System.out.print(firstName); // Output first name
Thread.sleep(aWhile); // Wait aWhile msec.
System.out.print(secondName+"\n"); // Output second name
}
} catch(InterruptedException e) { // Handle thread interruption
System.out.println(firstName + secondName + e); // Output the exception
}
} public static void main(String[] args) {
// Create three threads
Thread first = new Thread(new JumbleNames("Hopalong ", "Cassidy ", 200L));
Thread second = new Thread(new JumbleNames("Marilyn ", "Monroe ", 300L));
Thread third = new Thread(new JumbleNames("Slim ", "Pickens ", 500L)); // Set threads as daemon
first.setDaemon(true);
second.setDaemon(true);
third.setDaemon(true);
System.out.println("Press Enter when you have had enough...\n");
first.start(); // Start the first thread
second.start(); // Start the second thread
third.start(); // Start the third thread
try {
System.in.read(); // Wait until Enter key pressed
System.out.println("Enter pressed...\n"); } catch (IOException e) { // Handle IO exception
System.err.println(e); // Output the exception
}
System.out.println("Ending main()");
return;
} private String firstName; // Store for first name
private String secondName; // Store for second name
private long aWhile; // Delay in milliseconds
}

不能在这个构造函数中调用setDaemon()方法,因为这个类并非派生于Thread类。
在创建表示线程的对象之后并且在调用run()方法之前,需要调用setDaemon()方法。

在main()方法中,仍然为每个执行线程创建了Thread对象,但这次使用的构造函数把Runnable类型的对象作为参数。