這個類子類化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()方法程序的結果如下所示
Do it!
Definitely not!
Definitely not!
Definitely not!
Do it!
Do it!
Do it!
Definitely not!
Do it!
Definitely not!
Do it!
Definitely not!
Do it!
Do it!
Definitely not!
Do it!
Definitely not!
Definitely not!
Do it!
DONE! Do it!
Definitely not!
DONE! Definitely not!
正如你所看到的這兩個線程的輸出結果糾合到一起在一個單線程程序中所有的Do it!命令將一起打印後面跟著輸出Definitely not!
[] [] [] []
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27727.html