Demo18 :分別通過繼承Thread和實現Runnable接口來獲得線程

1.繼承Thread實現線程

package demo18;
/**
 * <p>Title: 繼承Thread,實現線程</p>
 * <p>Description: 通過繼承Thread類,實現其run方法,實現自己的線程</p>
 */
public class oneThread extends Thread {
/**
 *<br>方法說明:構造器,本類沒有使用
 *<br>輸入參數:
 *<br>返回類型:
 */
public oneThread() {

 }
/**
 *<br>方法說明:繼承Thread類必須實現的方法,當調用start方法時運行本方法
 *<br>輸入參數:
 *<br>返回類型:
 */
 public void run() {
  System.out.println("...............oneThread begining................");
  int flag = 0;
  while(true) {
    if(flag==20){
      System.out.println("\n...............oneThread end............. ");
      break;
    }
     for(int i=0;i<flag;i++)
       System.out.print("*");
     System.out.println("");
     flag++;
   try{
     //睡眠0.1秒
     sleep(100);
   }catch(Exception e){
   }   
  }
 }
/**
 *<br>方法說明:主方法。啓動本線程
 *<br>輸入參數:
 *<br>返回類型:
 */
 public static void main(String args[]) {
    new oneThread().start();
 }
}

運行結果:
這裏寫圖片描述

2.實現Runnable接口獲得線程

package demo18;
/**
 * <p>Title: 實現Runnable接口,獲得線程。</p>
 * <p>Description: 通過實現Runnable接口來獲得自己的線程(t2)。</p>
 */
public class twoThread implements Runnable {
/**
 *<br>方法說明:構造器。實際線程,並啓動這個線程。
 *<br>輸入參數:
 *<br>返回類型:
 */
 twoThread() { 
   //獲取當前的線程
   Thread t1 =Thread.currentThread(); 
   t1.setName("The first main thread"); 
   System.out.println("The running thread:" + t1); 
   //通過將本類(Runnable接口)和名稱構造一個線程
   Thread t2 = new Thread(this,"the second thread"); 
   System.out.println("creat another thread"); 
   //啓動線程
   t2.start(); 
   try { 
     System.out.println("first thread will sleep"); 
     Thread.sleep(3000); 
   }catch (InterruptedException e) {
     System.out.println("first thread has wrong"); 
   } 
   System.out.println("first thread exit"); 
 } 
/**
 *<br>方法說明:線程主體。實現run方法。
 *<br>輸入參數:
 *<br>返回類型:
 */
 public void run() { 
   try { 
     for (int i=0;i<5;i++) { 
       System.out.println("Sleep time for thread 2:"+i); 
       Thread.sleep(1000); 
     }
  } catch (InterruptedException e) {
    System.out.println("thread has wrong"); 
  }
  System.out.println("second thread exit"); 
 } 
/**
 *<br>方法說明:主方法
 *<br>輸入參數:
 *<br>返回類型:
 */
 public static void main(String args[]) { 
   new twoThread(); 
 } 
}


運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章