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類(lèi)
通過(guò)繼承Thread類(lèi),重寫(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類(lèi)的構(gòu)造函數(shù),傳入Ruanble接口的實(shí)現(xiàn)類(lèi)
因?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. 理解PHP5中static和const關(guān)鍵字2. IntelliJ IDEA安裝插件的方法步驟3. php模擬實(shí)現(xiàn)斗地主發(fā)牌4. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟5. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)6. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼7. Vuex localStorage的具體使用8. vue 使用localstorage實(shí)現(xiàn)面包屑的操作9. spring acegi security 1.0.0 發(fā)布10. MyBatis中的JdbcType映射使用詳解

網(wǎng)公網(wǎng)安備