在Java中,新建線程有多種方法。以下是一些常見的方法:
class MyThread extends Thread {
public void run() {
// 線程執行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 啟動線程
}
}
class MyRunnable implements Runnable {
public void run() {
// 線程執行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable); // 創建線程
thread.start(); // 啟動線程
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {
public String call() throws Exception {
// 線程執行的代碼,返回值類型為String
return "Hello, World!";
}
}
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
MyCallable myCallable = new MyCallable();
Future<String> future = executorService.submit(myCallable); // 提交任務
String result = future.get(); // 獲取任務結果
System.out.println(result); // 輸出結果
executorService.shutdown(); // 關閉線程池
}
}
import java.util.concurrent.CompletableFuture;
class MyCompletableFuture {
public static CompletableFuture<String> helloWorld() {
return CompletableFuture.supplyAsync(() -> {
// 線程執行的代碼,返回值類型為String
return "Hello, World!";
});
}
}
public class Main {
public static void main(String[] args) {
MyCompletableFuture.helloWorld().thenAccept(result -> {
System.out.println(result); // 輸出結果
});
}
}
這些方法都可以用于在Java中創建和啟動線程。你可以根據自己的需求和場景選擇合適的方法。