Java中創建子線程的方法有以下幾種:
public class MyThread extends Thread {
@Override
public void run() {
// 子線程的任務邏輯
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// 子線程的任務邏輯
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// 子線程的任務邏輯
return "子線程的返回結果";
}
public static void main(String[] args) {
MyCallable callable = new MyCallable();
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(callable);
try {
String result = future.get();
System.out.println("子線程的返回結果:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
這些方法都可以創建一個子線程并執行一些任務邏輯,具體使用哪種方法取決于需求和代碼的結構。