聊聊創(chuàng)建多線程的四種方式,你知道幾種?
Java 創(chuàng)建多線程的4種方式包括以下幾種:
- 繼承Thread類
定義子類:通過繼承Thread類,并重寫其run()方法來定義線程要執(zhí)行的任務。
創(chuàng)建實例并啟動:創(chuàng)建該子類的實例,然后調(diào)用start()方法啟動線程。
示例代碼:
public class Mythread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName() + ":" + i);
}
}
public static void main(String[] args) {
Mythread t1 = new Mythread();
Mythread t2 = new Mythread();
Mythread t3 = new Mythread();
t1.start();
t2.start();
t3.start();
}
}
- 實現(xiàn)Runnable接口
定義實現(xiàn)類:實現(xiàn)Runnable接口,并重寫其run()方法。
創(chuàng)建Thread對象并啟動:將實現(xiàn)類實例作為參數(shù)傳給Thread對象的構(gòu)造函數(shù),然后調(diào)用start()方法啟動線程。
示例代碼:
public class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread, "線程1");
Thread thread2 = new Thread(myThread, "線程2");
Thread thread3 = new Thread(myThread, "線程3");
thread1.start();
thread2.start();
thread3.start();
}
}
- 使用Callable和Future接口
定義Callable實現(xiàn)類:實現(xiàn)Callable接口并重寫其call()方法。
使用FutureTask包裝:用FutureTask類包裝Callable對象,并將其傳遞給Thread對象。
獲取結(jié)果:通過FutureTask對象的get()方法獲取線程執(zhí)行的結(jié)果。
示例代碼:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyThread implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
return "Hello Tom";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread d = new MyThread();
FutureTask<String> futureTask = new FutureTask<>(d);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println("返回值:" + futureTask.get()); // 阻塞直到任務完成并返回結(jié)果
}
}
- 使用線程池(Executor)
創(chuàng)建線程池:通過Executors工具類創(chuàng)建一個線程池,如newFixedThreadPool、newCachedThreadPool等。
提交任務:將實現(xiàn)了Runnable或Callable接口的任務提交給線程池執(zhí)行。
示例代碼:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadPool implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
MyThreadPool myThreadPool = new MyThreadPool();
executorService.submit(myThreadPool); // 提交任務到線程池
}
executorService.shutdown(); // 關閉線程池
}
}
Java中創(chuàng)建多線程的方式主要包括繼承Thread類、實現(xiàn)Runnable接口、使用Callable和Future接口以及利用線程池。每種方式都有其適用場景和特點,可以根據(jù)具體需求選擇合適的方式來實現(xiàn)多線程編程。