在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());
}
}
創建并啟動線程:
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start(); // 啟動線程1
thread2.start(); // 啟動線程2
}
}
synchronized關鍵字或者Lock接口來實現線程同步。wait()、notify()和notifyAll()方法來實現線程間的通信。下面是一個完整的示例代碼,展示了如何使用Runnable接口實現多線程:
class MyRunnable implements Runnable {
private int count = 0;
@Override
public void run() {
while (count < 5) {
synchronized (this) {
System.out.println("線程 " + Thread.currentThread().getName() + " 計數: " + count);
count++;
try {
Thread.sleep(1000); // 讓線程休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable, "線程1");
Thread thread2 = new Thread(runnable, "線程2");
thread1.start();
thread2.start();
}
}
在這個示例中,兩個線程共享同一個MyRunnable實例,并且通過synchronized關鍵字確保對count變量的訪問是線程安全的。每個線程會打印計數器的值,并讓線程休眠1秒。