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類,重寫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)寫為
public static void main(String[] args) { new Thread(() -> { System.out.println('新線程'); }).start();}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS hack用法案例詳解2. input submit、button和回車鍵提交數(shù)據(jù)詳解3. 使用HttpClient增刪改查ASP.NET Web API服務(wù)4. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除5. 詳解盒子端CSS動(dòng)畫(huà)性能提升6. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式7. Jsp+Servlet實(shí)現(xiàn)文件上傳下載 刪除上傳文件(三)8. 利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息的實(shí)現(xiàn)方法9. 詳解瀏覽器的緩存機(jī)制10. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?
