在Ubuntu中,使用Java實現多線程主要有兩種方法:繼承Thread類或實現Runnable接口。下面分別介紹這兩種方法的實現步驟。
步驟1:創建一個類,繼承自Thread類。
class MyThread extends Thread {
public void run() {
// 在這里編寫多線程執行的代碼
System.out.println("線程正在運行: " + Thread.currentThread().getName());
}
}
步驟2:創建MyThread類的對象,并調用start()方法啟動線程。
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // 啟動線程t1
t2.start(); // 啟動線程t2
}
}
步驟1:創建一個類,實現Runnable接口。
class MyRunnable implements Runnable {
public void run() {
// 在這里編寫多線程執行的代碼
System.out.println("線程正在運行: " + Thread.currentThread().getName());
}
}
步驟2:創建MyRunnable類的對象,并將其傳遞給Thread類的構造函數。然后調用Thread對象的start()方法啟動線程。
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(); // 啟動線程t1
t2.start(); // 啟動線程t2
}
}
注意:實現Runnable接口的方法更加靈活,因為它允許你的類繼承其他類。而繼承Thread類的方法則不能繼承其他類,因為Java不支持多繼承。在實際開發中,推薦使用實現Runnable接口的方法來實現多線程。