在Java中,創建線程有兩種主要方法:
下面是這兩種方法的示例:
方法1:繼承Thread類
// 創建一個名為MyThread的類,該類繼承自Thread類
class MyThread extends Thread {
@Override
public void run() {
// 在這里編寫你的線程代碼
System.out.println("線程正在運行...");
}
}
public class Main {
public static void main(String[] args) {
// 創建MyThread對象
MyThread myThread = new MyThread();
// 啟動線程
myThread.start();
}
}
方法2:實現Runnable接口
// 創建一個名為MyRunnable的類,該類實現Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
// 在這里編寫你的線程代碼
System.out.println("線程正在運行...");
}
}
public class Main {
public static void main(String[] args) {
// 創建MyRunnable對象
MyRunnable myRunnable = new MyRunnable();
// 創建Thread對象并將MyRunnable對象作為參數傳遞
Thread thread = new Thread(myRunnable);
// 啟動線程
thread.start();
}
}
另外,你還可以使用Java的ExecutorService
和Callable
接口來更高級地管理線程。這里是一個使用ExecutorService
的示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
// 創建一個固定大小的線程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
// 提交任務到線程池
executorService.submit(new MyRunnable());
executorService.submit(new MyRunnable());
// 關閉線程池
executorService.shutdown();
}
}
這里是一個使用Callable
接口的示例:
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// 在這里編寫你的線程代碼
return "線程執行完成";
}
}
public class Main {
public static void main(String[] args) {
// 創建一個單線程的執行器
ExecutorService executorService = Executors.newSingleThreadExecutor();
// 提交任務到執行器并獲取Future對象
Future<String> future = executorService.submit(new MyCallable());
try {
// 獲取任務執行結果
String result = future.get();
System.out.println("線程執行結果: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// 關閉執行器
executorService.shutdown();
}
}