Java實現多線程的方法有以下幾種:
public class MyThread extends Thread {
public void run() {
// 線程的執行邏輯
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 啟動線程
}
}
public class MyRunnable implements Runnable {
public void run() {
// 線程的執行邏輯
}
}
public class Main {
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<Integer> {
public Integer call() {
// 線程的執行邏輯,返回一個結果
return 1;
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyCallable callable = new MyCallable();
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callable);
int result = future.get(); // 獲取任務的返回結果
System.out.println(result);
executorService.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyRunnable implements Runnable {
public void run() {
// 線程的執行邏輯
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10); // 創建一個固定大小的線程池
executorService.execute(new MyRunnable()); // 提交任務
executorService.shutdown(); // 關閉線程池
}
}