我想了解線程並在互聯網上找到一些例子。這是一個java類,每3秒輸出一次「hello,world」。但我有一種感覺,關於創建Runable對象的部分是多餘的。線程和創建對象
而是寫作的
Runnable r = new Runnable(){ public void run(){...some actions...}};
我可以把方法run()
別的地方,便於閱讀?
這是我有:
public class TickTock extends Thread {
public static void main (String[] arg){
Runnable r = new Runnable(){
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
};
Thread thr = new Thread(r);
thr.start();
}
這就是我想要的東西來完成
public static void main (String[] arg){
Runnable r = new Runnable() //so no run() method here,
//but where should I put run()
Thread thr = new Thread(r);
thr.start();
}
除了下面實際的答案,考慮學習如何使用IDE的重構工具做這樣的事情(車削匿名類成內部類或「正常」非嵌套類)。 – hyde