首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

[JAVA100例] 第61例:實現 Runnable 接口創建線程

     編輯:Java 相關知識

本例演示通過實現 Runnable 接口創建線程:主線程構造 Thread(this, name) 將自身作為任務傳入,啟動子線程並發執行。

核心代碼

public class twothread implements Runnable {
  twothread() {
    Thread t1 = Thread.currentThread();
    t1.setName("The first main thread");
    System.out.println("The running thread: " + t1);

    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");
  }

  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");
  }

  public static void main(String args[]) { new twothread(); }
}

Runnable vs Thread 繼承對比

維度繼承 Thread實現 Runnable
繼承限制單繼承,無法繼承其他類無限制,可繼承任意類
任務與線程耦合(類即線程)分離(任務可被多線程執行)
共享數據需額外傳遞自然共享 this 實例字段
線程池適配不直接支援完美支援 ExecutorService.submit(Runnable)
Lambda 支援不支援函數式接口,完美支援 Lambda

核心優勢:任務復用

Runnable task = new MyTask();
new Thread(task, "T1").start();
new Thread(task, "T2").start();  // 同一任務實例被多線程執行
executor.submit(task);           // 線程池執行

現代最佳實踐

  1. 優先實現 Runnable(或 Callable 有返回值)
  2. 使用 Lambda:Runnable r = () -> { ... };
  3. 配合 ExecutorService:executor.submit(runnable)
  4. 需返回值用 Callable:Future future = executor.submit(callable)
  5. 避免直接 new Thread():生產環境統一使用線程池

代碼改進建議

  • 構造器中啟動線程屬於「this 逃逸」,建議提供顯式 start() 方法
  • Thread.sleep() 捕獲 InterruptedException 應重設置中斷標誌:Thread.currentThread().interrupt()
  • 主線程退出不代表程序結束(非守護線程仍在運行),演示中主線程先結束但子線程繼續
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved