簡(jiǎn)單了解Java多線程實(shí)現(xiàn)的四種方式
第一種方式為繼承Thread類然后重寫run方法再調(diào)用start方法,因?yàn)閖ava為單繼承多實(shí)現(xiàn),所以不建議使用這種方式,代碼如下:
public class Demo extends Thread{ public static void main(String[] args) { new Demo().start(); } @Override public void run() { System.out.println('繼承Thread類實(shí)現(xiàn)多線程'); }}
第二種為實(shí)現(xiàn)Runnable接口方式,該方式用的較多,代碼如下:
public class Demo2 implements Runnable{ public static void main(String[] args) { new Thread(new Demo2()).start(); } @Override public void run() { System.out.println('實(shí)現(xiàn)Runnable接口的多線程'); }}
第三種為實(shí)現(xiàn)Callable接口方式,該方式run方法具有返回值,代碼如下:
public class Demo3 implements Callable { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask task=new FutureTask(new Demo3()); new Thread(task).start(); System.out.println(task.get()); } @Override public String call() throws Exception { return '實(shí)現(xiàn)Callable接口的多線程'; }}
第四種是采用線程池的方式,代碼如下:
public class Demo4 { public static void main(String[] args) { ExecutorService executorService= Executors.newCachedThreadPool(); executorService.execute(new Runnable() { @Override public void run() {System.out.println('線程池實(shí)現(xiàn)多線程'); } });executorService.shutdown(); }}
從上面我們可以看出線程的調(diào)用都是采用start()方法,那么調(diào)用直接調(diào)用run()方法其實(shí)也是可以輸出結(jié)果的,但是有著本質(zhì)的區(qū)別,因?yàn)檎{(diào)用start()方法會(huì)使得當(dāng)前線程的數(shù)量增加,而單純得調(diào)用run()方法是不會(huì)的,在start()方法的內(nèi)部其實(shí)包含了調(diào)用run()方法。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解2. Nginx+php配置文件及原理解析3. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法4. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法5. 淺談python出錯(cuò)時(shí)traceback的解讀6. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼7. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題8. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向9. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解10. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析
