控制臺程序。
除了定義Thread新的子類外,還可以在類中實現Runnable接口。您會發現這比從Thread類派生子類更方便,因為在實現Runnable接口時可以從不是Thread的類派生子類,并且仍然表示線程。Java只允許有單個基類,如果類派生于Thread,就不能再繼承其他類中的功能。Runnabel接口只定義了方法run(),這個方法在啟動線程時執行。
1 import java.io.IOException; 2 3 public class JumbleNames implements Runnable { 4 // Constructor 5 public JumbleNames(String firstName, String secondName, long delay) { 6 this.firstName = firstName; // Store the first name 7 this.secondName = secondName; // Store the second name 8 aWhile = delay; // Store the delay 9 } 10 11 // Method where thread execution will start 12 public void run() { 13 try { 14 while(true) { // Loop indefinitely... 15 System.out.print(firstName); // Output first name 16 Thread.sleep(aWhile); // Wait aWhile msec. 17 System.out.print(secondName+"\n"); // Output second name 18 } 19 } catch(InterruptedException e) { // Handle thread interruption 20 System.out.println(firstName + secondName + e); // Output the exception 21 } 22 } 23 24 public static void main(String[] args) { 25 // Create three threads 26 Thread first = new Thread(new JumbleNames("Hopalong ", "Cassidy ", 200L)); 27 Thread second = new Thread(new JumbleNames("Marilyn ", "Monroe ", 300L)); 28 Thread third = new Thread(new JumbleNames("Slim ", "Pickens ", 500L)); 29 30 // Set threads as daemon 31 first.setDaemon(true); 32 second.setDaemon(true); 33 third.setDaemon(true); 34 System.out.println("Press Enter when you have had enough...\n"); 35 first.start(); // Start the first thread 36 second.start(); // Start the second thread 37 third.start(); // Start the third thread 38 try { 39 System.in.read(); // Wait until Enter key pressed 40 System.out.println("Enter pressed...\n"); 41 42 } catch (IOException e) { // Handle IO exception 43 System.err.println(e); // Output the exception 44 } 45 System.out.println("Ending main()"); 46 return; 47 } 48 49 private String firstName; // Store for first name 50 private String secondName; // Store for second name 51 private long aWhile; // Delay in milliseconds 52 }
不能在這個構造函數中調用setDaemon()方法,因為這個類并非派生于Thread類。
在創建表示線程的對象之后并且在調用run()方法之前,需要調用setDaemon()方法。
在main()方法中,仍然為每個執行線程創建了Thread對象,但這次使用的構造函數把Runnable類型的對象作為參數。
?