public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.PRintln(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); } } 這個類子類化Thread并且提供它自己的run()方法。上面代碼中的函數運行一個循環來打印傳送過來的字符串到屏幕上,然后等待一個隨機的時間數目。在循環十次后,該函數打印"DONE!",然后退出-并由它殺死這個線程。下面是創建線程的主函數:
public class TwoThreadsDemo { public static void main (String[] args) { new SimpleThread("Do it!").start(); new SimpleThread("Definitely not!").start(); } } 注重該代碼極為簡單:函數開始,給定一個名字(它是該線程將要打印輸出的字符串)并且調用start()。然后,start()將調用run()方法。程序的結果如下所示:
0 Do it! 0 Definitely not! 1 Definitely not! 2 Definitely not! 1 Do it! 2 Do it! 3 Do it! 3 Definitely not! 4 Do it! 4 Definitely not! 5 Do it! 5 Definitely not! 6 Do it! 7 Do it! 6 Definitely not! 8 Do it! 7 Definitely not! 8 Definitely not! 9 Do it! DONE! Do it! 9 Definitely not! DONE! Definitely not! 正如你所看到的,這兩個線程的輸出結果糾合到一起。在一個單線程程序中,所有的"Do it!"命令將一起打印,后面跟著輸出"Definitely not!"。