在Java中,實現多線程主要有兩種方法:繼承Thread類或實現Runnable接口。以下是在Ubuntu上使用這兩種方法實現多線程的示例。
創建一個名為MyThread的類,繼承Thread類,并重寫run()方法。在run()方法中編寫線程執行的代碼。
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
創建一個名為Main的類,用于啟動線程。
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
編譯并運行Main類:
javac Main.java
java Main
創建一個名為MyRunnable的類,實現Runnable接口,并重寫run()方法。在run()方法中編寫線程執行的代碼。
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
創建一個名為Main的類,用于啟動線程。
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();
}
}
編譯并運行Main類:
javac Main.java
java Main
這兩種方法都可以在Ubuntu上實現多線程。在實際應用中,推薦使用實現Runnable接口的方法,因為它更符合面向對象的設計原則,避免了單繼承的限制。