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

Java 多線程創建方式二:實現 Runnable 接口、Thread 構造器傳入與啟動

     編輯:Java 相關知識

Runnable 接口創建線程兩步走

  1. 實現 Runnable 接口,重寫 run()
  2. 創建 Thread 實例,構造器傳入 Runnable 實例
  3. 調用 Thread.start() 啟動線程

代碼示例

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        MyRunnable t1 = new MyRunnable();
        MyRunnable t2 = new MyRunnable();
        Thread thread1 = new Thread(t1, "MyThread1");
        Thread thread2 = new Thread(t2);
        thread2.setName("MyThread2");
        thread1.start();
        thread2.start();
    }
}

運行結果

MyThread1
MyThread2

核心要點

  • Thread 實現了 Runnable,所以 Thread 子類實例也可作為 target
  • 線程名可通過構造器或 setName() 設置
  • 必須調用 start() 而非直接調用 run() (後者為主線程同步執行)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved