您好,登錄后才能下訂單哦!
這篇文章主要講解了Java多線程的實(shí)現(xiàn)方法,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
多線程三種主要實(shí)現(xiàn)方式:繼承Thread類,實(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類 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類 new MyThread().start(); //2.lambda與繼承Thread類類//1.繼承Thread類似,最簡(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來同時(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來實(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é)果:
看完上述內(nèi)容,是不是對(duì)Java多線程的實(shí)現(xiàn)方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。