簡單了解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()方法會使得當(dāng)前線程的數(shù)量增加,而單純得調(diào)用run()方法是不會的,在start()方法的內(nèi)部其實(shí)包含了調(diào)用run()方法。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JavaWeb Servlet中url-pattern的使用2. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達(dá)式3. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼4. React優(yōu)雅的封裝SvgIcon組件示例5. 輕松學(xué)習(xí)XML教程6. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究7. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)8. jsp中sitemesh修改tagRule技術(shù)分享9. ASP基礎(chǔ)知識VBScript基本元素講解10. 詳解瀏覽器的緩存機(jī)制
