Java實(shí)現(xiàn)多線程的方法有以下幾種:
public class MyThread extends Thread {
public void run() {
// 線程的執(zhí)行邏輯
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 啟動(dòng)線程
}
}
public class MyRunnable implements Runnable {
public void run() {
// 線程的執(zhí)行邏輯
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 啟動(dòng)線程
}
}
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() {
// 線程的執(zhí)行邏輯,返回一個(gè)結(jié)果
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(); // 獲取任務(wù)的返回結(jié)果
System.out.println(result);
executorService.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyRunnable implements Runnable {
public void run() {
// 線程的執(zhí)行邏輯
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10); // 創(chuàng)建一個(gè)固定大小的線程池
executorService.execute(new MyRunnable()); // 提交任務(wù)
executorService.shutdown(); // 關(guān)閉線程池
}
}