在Java中,開啟線程有多種方法:
public class MyThread extends Thread {
public void run() {
// 線程執行邏輯
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
public class MyRunnable implements Runnable {
public void run() {
// 線程執行邏輯
}
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new Runnable() {
public void run() {
// 線程執行邏輯
}
});
executor.shutdown();
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Integer> future = executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
// 線程執行邏輯
return 42;
}
});
executor.shutdown();
try {
int result = future.get();
// 使用得到的結果
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
這些都是Java中常用的開啟線程的方法,可以根據具體需求選擇適合的方法來創建和管理線程。