java實(shí)現(xiàn)多線程的方法有哪些

小億
100
2023-08-12 04:27:04

Java實(shí)現(xiàn)多線程的方法有以下幾種:

  1. 繼承Thread類:創(chuàng)建一個(gè)繼承自Thread類的子類,并重寫run方法,通過調(diào)用start方法啟動(dòng)線程。
class MyThread extends Thread {
public void run() {
// 線程執(zhí)行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
  1. 實(shí)現(xiàn)Runnable接口:創(chuàng)建一個(gè)實(shí)現(xiàn)了Runnable接口的類,并實(shí)現(xiàn)run方法,通過創(chuàng)建Thread對(duì)象并將其作為參數(shù)傳遞,然后調(diào)用start方法啟動(dòng)線程。
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();
}
}
  1. 使用Callable和Future:創(chuàng)建一個(gè)實(shí)現(xiàn)了Callable接口的類,并實(shí)現(xiàn)call方法,通過創(chuàng)建ExecutorService線程池對(duì)象,調(diào)用submit方法提交任務(wù)并返回Future對(duì)象,通過調(diào)用Future對(duì)象的get方法獲取線程執(zhí)行結(jié)果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<Integer> {
public Integer call() {
// 線程執(zhí)行的代碼
return 0;
}
}
public class Main {
public static void main(String[] args) {
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(callable);
try {
Integer result = future.get();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
}
  1. 使用線程池:創(chuàng)建一個(gè)ExecutorService線程池對(duì)象,通過調(diào)用execute方法提交任務(wù),線程池會(huì)自動(dòng)管理線程的創(chuàng)建和銷毀。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
executor.execute(new Runnable() {
public void run() {
// 線程執(zhí)行的代碼
}
});
}
executor.shutdown();
}
}

0