Java創(chuàng)建多線程異步執(zhí)行實(shí)現(xiàn)代碼解析
實(shí)現(xiàn)Runable接口
通過(guò)實(shí)現(xiàn)Runable接口中的run()方法
public class ThreadTest implements Runnable { public static void main(String[] args) { Thread thread = new Thread(new ThreadTest()); thread.start(); } @Override public void run() { System.out.println('Runable 方式創(chuàng)建的新線程'); }}
繼承Thread類
通過(guò)繼承Thread類,重寫(xiě)run()方法,隨后實(shí)例調(diào)用start()方法啟動(dòng)
public class ThreadTest extends Thread{ @Override public void run() { System.out.println('Thread 方式創(chuàng)建的線程'); } public static void main(String[] args) { new ThreadTest().start(); }}
對(duì)于第一種方式,其本質(zhì)就是調(diào)用Thread類的構(gòu)造函數(shù),傳入Ruanble接口的實(shí)現(xiàn)類
因?yàn)镽unable接口是一個(gè)FunctionalInterface, 因此也可以使用Lambda表達(dá)式簡(jiǎn)寫(xiě)為
public static void main(String[] args) { new Thread(() -> { System.out.println('新線程'); }).start();}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Spring security 自定義過(guò)濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)2. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析3. python學(xué)習(xí)之plot函數(shù)的使用教程4. python wsgiref源碼解析5. 一文搞懂 parseInt()函數(shù)異常行為6. python 實(shí)現(xiàn)關(guān)聯(lián)規(guī)則算法Apriori的示例7. ASP.NET MVC使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)碼8. python 實(shí)現(xiàn)"神經(jīng)衰弱"翻牌游戲9. python tkinter實(shí)現(xiàn)下載進(jìn)度條及抖音視頻去水印原理10. Python基于百度AI實(shí)現(xiàn)抓取表情包
