Java多線程三種主要實(shí)現(xiàn)方式解析
多線程三種主要實(shí)現(xiàn)方式:繼承Thread類(lèi),實(shí)現(xiàn)Runnable接口、Callable和Futrue。
一、簡(jiǎn)單實(shí)現(xiàn)
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;import java.util.concurrent.TimeUnit;public class T02_HowToCreateThread { //1.繼承Thread類(lèi) static class MyThread extends Thread{ @Override public void run() { System.out.println('MyThread-->'); } } //3.實(shí)現(xiàn)Runnable接口 static class MyRun implements Runnable{ @Override public void run() { System.out.println('MyRunable-->'); } } //4.實(shí)現(xiàn)Callable接口 static class MyCall implements Callable{ @Override public Object call() throws Exception { System.out.println('myCallable-->'); return 1; } } public static void main(String[] args) throws ExecutionException, InterruptedException { //1.繼承Thread類(lèi) new MyThread().start(); //2.lambda與繼承Thread類(lèi)類(lèi)//1.繼承Thread類(lèi)似,最簡(jiǎn)單 new Thread(()->{ System.out.println('lambda-->'); }).start(); //3.實(shí)現(xiàn)Runnable接口 new Thread(new MyRun()).start(); new Thread(new Runnable() { @Override public void run() {System.out.println('simple->Runnable'); } }).start(); //4.實(shí)現(xiàn)Callable接口,并用包裝器FutureTask來(lái)同時(shí)實(shí)現(xiàn)Runable、Callable兩個(gè)接口,可帶返回結(jié)果 MyCall mycall = new MyCall(); FutureTask futureTask = new FutureTask(mycall); new Thread(futureTask).start(); System.out.println(futureTask.get()); }}
二、使用ExecutorService、Callable和Future一起實(shí)現(xiàn)帶返回值
import java.util.ArrayList;import java.util.List;import java.util.concurrent.*;/** * 使用ExecutorsService、Callable、Future來(lái)實(shí)現(xiàn)多個(gè)帶返回值的線程 */public class T02_HowToCreateThread02 { static class MyCallable implements Callable{ private int taskNum; public MyCallable(int taskNum){ this.taskNum = taskNum; } @Override public Object call() throws Exception { System.out.println('任務(wù)'+taskNum); return 'MyCallable.call()-->task'+taskNum; } } public static void main(String[] args) throws ExecutionException, InterruptedException { int num = 5; //創(chuàng)建一個(gè)線程池 ExecutorService pool = Executors.newFixedThreadPool(num); List<Future> futureList = new ArrayList<Future>(); for (int i = 0; i < num; i++){ MyCallable mc = new MyCallable(i); //執(zhí)行任務(wù),并返回值 Future future = pool.submit(mc); futureList.add(future); } pool.shutdown(); for (Future f: futureList){ System.out.println(f.get()); } }}
結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. XHTML 1.0:標(biāo)記新的開(kāi)端3. HTML5 Canvas繪制圖形從入門(mén)到精通4. XML解析錯(cuò)誤:未組織好 的解決辦法5. ASP基礎(chǔ)知識(shí)VBScript基本元素講解6. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. 利用CSS3新特性創(chuàng)建透明邊框三角9. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法10. XML入門(mén)的常見(jiàn)問(wèn)題(四)
