返回列表 發帖

執行緒 (三)

本帖最後由 tonyh 於 2019-11-23 14:20 編輯

自訂類別,繼承Thread類別,建立執行緒。

  1. public class Ch123 {
  2.         private MyThread th;
  3.         
  4.         Ch123()
  5.         {
  6.                 th=new MyThread();
  7.                 th.start();
  8.         }
  9.         
  10.         public static void main(String[] args) {
  11.                 new Ch123();        
  12.         }
  13. }

  14. class MyThread extends Thread
  15. {
  16.         public void run()
  17.         {
  18.                 for(int i=5; i>=1; i--)
  19.                 {
  20.                         System.out.println(i+"秒");
  21.                         try {
  22.                                 sleep(1000);
  23.                         } catch (InterruptedException e) {}
  24.                 }
  25.                 System.out.println("時間到!");
  26.                 System.out.println("執行緒名稱: "+Thread.currentThread().getName());
  27.         }
  28. }
複製代碼
  1. public class Ch125{
  2.         MyThread th;
  3.        
  4.         Ch125()
  5.         {
  6.                 th=new MyThread();
  7.                 th.start();
  8.         }
  9.         public static void main(String[] args) {
  10.              new Ch125();       
  11.         }
  12.        
  13.         class MyThread extends Thread
  14.         {
  15.                 public void run()
  16.                 {
  17.                         for(int i=5; i>=1; i--)
  18.                         {
  19.                                 System.out.println(i+"秒");
  20.                                 try {
  21.                                         sleep(1000);
  22.                                 } catch (InterruptedException e) {
  23.                         System.out.println(e);
  24.                                 }
  25.                         }
  26.                         System.out.println("時間到!");
  27.                         System.out.println("執行緒名稱:"+Thread.currentThread().getName());       
  28.                 }
  29.     }
  30. }
複製代碼

返回列表