在Ubuntu下使用Java實現多線程,主要有兩種方法:繼承Thread
類和實現Runnable
接口。下面分別介紹這兩種方法的實現步驟。
Thread
類創建一個繼承自Thread
類的子類:
class MyThread extends Thread {
@Override
public void run() {
// 線程執行的代碼
System.out.println("線程正在運行: " + Thread.currentThread().getName());
}
}
創建并啟動線程:
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // 啟動線程1
thread2.start(); // 啟動線程2
}
}
Runnable
接口創建一個實現Runnable
接口的類:
class MyRunnable implements Runnable {
@Override
public void run() {
// 線程執行的代碼
System.out.println("線程正在運行: " + Thread.currentThread().getName());
}
}
創建一個Thread
對象,并將Runnable
對象作為參數傳遞給它:
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread1.start(); // 啟動線程1
thread2.start(); // 啟動線程2
}
}
wait()
、notify()
和notifyAll()
方法來實現線程間的通信。ExecutorService
來管理線程池,提高性能和資源利用率。下面是一個完整的示例代碼,展示了如何使用Runnable
接口實現多線程:
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("線程 " + Thread.currentThread().getName() + " 正在運行: " + i);
try {
Thread.sleep(1000); // 模擬線程執行時間
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable, "線程1");
Thread thread2 = new Thread(myRunnable, "線程2");
thread1.start();
thread2.start();
}
}
運行上述代碼,你會看到兩個線程交替執行,并且每個線程都會打印出自己的名稱和循環計數。