1、Java實(shí)現(xiàn)多線程主要有三種方式:
- (1)繼承Thread類
- (2)實(shí)現(xiàn)Runnable接口
- (3)使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的多線程。
其中前兩種方式線程執(zhí)行完后都沒有返回值,只有最后一種是帶返回值的。
2、方式一:繼承Thread類
Thread類本質(zhì)上也是實(shí)現(xiàn)了Runnable接口的一個(gè)類,它代表一個(gè)線程的實(shí)例。
啟動(dòng)線程的唯一方法就是通過Thread類的start()方法。start()方法是一個(gè)native方法,它將啟動(dòng)一個(gè)新線程,并執(zhí)行run()方法。
通過自己的類直接extends Thread,并復(fù)寫run()方法,就可以啟動(dòng)新線程并執(zhí)行自己定義的run()方法。
//實(shí)現(xiàn)多線程方式一:繼承Thread類
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("啟動(dòng)一個(gè)新線程, 并執(zhí)行run()方法.");
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
3、方式二:實(shí)現(xiàn)Runnable接口
如果自己的類已經(jīng)extends另一個(gè)類,就無法直接extends Thread,此時(shí),必須通過實(shí)現(xiàn)Runnable接口來創(chuàng)建線程。
public class Test {
public static void main(String[] args) {
Thread newThread = new Thread(new MyThread());
newThread.start();
}
}
class OtherClass {
}
//實(shí)現(xiàn)多線程方式二:實(shí)現(xiàn)Runnable接口
class MyThread extends OtherClass implements Runnable {
@Override
public void run() {
System.out.println("創(chuàng)建線程, 并執(zhí)行run()方法.");
}
}
4、方式二:使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的多線程
需要開啟新線程執(zhí)行有返回值的任務(wù)必須實(shí)現(xiàn)Callable接口。
執(zhí)行Callable任務(wù)后,可以獲取一個(gè)Future的對(duì)象,在該對(duì)象上調(diào)用get就可以獲取到Callable任務(wù)返回的Object結(jié)果了。
結(jié)合線程池接口ExecutorService就可以實(shí)現(xiàn)有返回結(jié)果的多線程了。
import java.util.concurrent.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
/**
* 有返回值的線程
* @author Tao
*
*/
public class Test {
public static void main(String[] args) throws
InterruptedException, ExecutionException {
int poolSize = 10; //線程池大小
//創(chuàng)建一個(gè)線程池
ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
//創(chuàng)建多個(gè)Task
List<Future<Object>> futureList = new ArrayList<>();
for(int i = 0; i < poolSize; i++) {
Callable<Object> task = new MyTask("NO" + i);
//放入線程池中執(zhí)行任務(wù)并取得返回值
Future<Object> future = threadPool.submit(task);
futureList.add(future);
}
//關(guān)閉線程池
threadPool.shutdown();
//輸出所有結(jié)果
for(Future<Object> f : futureList) {
System.out.println(f.get().toString());
}
}
}
//定義任務(wù)類
class MyTask implements Callable<Object> {
private String taskNum; //任務(wù)編號(hào)
public MyTask(String taskNum) {
this.taskNum = taskNum;
}
@Override
public Object call() throws Exception {
System.out.println("任務(wù) " + taskNum + " 啟動(dòng)了...");
Date startTime = new Date();
Thread.sleep(1000);
Date endTime = new Date();
long costTime = endTime.getTime() - startTime.getTime();
System.out.println("任務(wù) " + taskNum + " 執(zhí)行完畢.");
//返回值
return taskNum + " 任務(wù)返回運(yùn)行結(jié)果, 任務(wù)執(zhí)行耗費(fèi)時(shí)間【" + costTime + "毫秒】";
}
}