如果需要執行一個比較耗時的任務,應該使用獨立線程。
(1)将任務代碼移到實作了Runnable接口的類的run方法中。
class MyRunnableimplements Runnable
{
public void run()
{
code
}
}
(2)建立一個類對象
Runnable r = newMyRunnable();
(3)由Runnable 建立一個Thread對象:
Threadt = new Thread(r);
(4)啟動線程
t.start();
另一種建立一個線程:
class MyThread extends Thread
{
publicvoid run()
{
code
}
}