溫馨提示×

java 新建線程如何用

小樊
93
2024-11-29 18:45:56
欄目: 編程語言

在Java中,創建一個新線程有兩種主要方法:

  1. 繼承Thread類
  2. 實現Runnable接口

下面是兩種方法的示例:

方法1:繼承Thread類

class MyThread extends Thread {
    public void run() {
        // 在這里編寫你的代碼
        System.out.println("線程正在運行...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start(); // 啟動新線程
    }
}

方法2:實現Runnable接口

class MyRunnable implements Runnable {
    public void run() {
        // 在這里編寫你的代碼
        System.out.println("線程正在運行...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable); // 創建新線程
        thread.start(); // 啟動新線程
    }
}

這兩種方法都可以創建一個新線程并啟動它。你可以根據自己的需求選擇合適的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女