溫馨提示×

Java在Linux上如何實現多線程

小樊
38
2025-08-07 02:45:29
欄目: 編程語言

在Java中,實現多線程主要有兩種方法:繼承Thread類或實現Runnable接口。以下是在Linux上使用這兩種方法實現多線程的示例。

  1. 繼承Thread類:
class MyThread extends Thread {
    public void run() {
        System.out.println("線程正在運行: " + Thread.currentThread().getName());
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();
    }
}
  1. 實現Runnable接口:
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("線程正在運行: " + Thread.currentThread().getName());
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        Thread t2 = new Thread(myRunnable);
        t1.start();
        t2.start();
    }
}

在這兩個示例中,我們創建了兩個線程并啟動它們。在Linux上,你可以使用javac命令編譯這些Java文件,然后使用java命令運行編譯后的類。

編譯:

javac Main.java

運行:

java Main

這將輸出類似以下內容:

線程正在運行: Thread-0
線程正在運行: Thread-1

請注意,線程的執行順序可能會有所不同,因為它們是并發運行的。

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