自訂類別,繼承Thread類別,建立執行緒。
- public class Ch123 {
- private MyThread th;
-
- Ch123()
- {
- th=new MyThread();
- th.start();
- }
-
- public static void main(String[] args) {
- new Ch123();
- }
- }
- class MyThread extends Thread
- {
- public void run()
- {
- for(int i=5; i>=1; i--)
- {
- System.out.println(i+"秒");
- try {
- sleep(1000);
- } catch (InterruptedException e) {}
- }
- System.out.println("時間到!");
- System.out.println("執行緒名稱: "+Thread.currentThread().getName());
- }
- }
複製代碼- public class Ch125{
- MyThread th;
-
- Ch125()
- {
- th=new MyThread();
- th.start();
- }
- public static void main(String[] args) {
- new Ch125();
- }
-
- class MyThread extends Thread
- {
- public void run()
- {
- for(int i=5; i>=1; i--)
- {
- System.out.println(i+"秒");
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- System.out.println(e);
- }
- }
- System.out.println("時間到!");
- System.out.println("執行緒名稱:"+Thread.currentThread().getName());
- }
- }
- }
複製代碼 |