创建线程的方式_创建线程有几种不同的方式?
生活随笔
收集整理的這篇文章主要介紹了
创建线程的方式_创建线程有几种不同的方式?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
方式可以用來創(chuàng)建線程
1)繼承Thread類
2)實現(xiàn)Runnable接口
3)應(yīng)用程序可以適用Executor框架來創(chuàng)建線程池
實現(xiàn)了Runnable接口這種方式更受歡迎,因為這不需要繼承Thread類。在應(yīng)用設(shè)計中已經(jīng)繼承了別的對象的情況下,這需要多繼承,而Java不支持多繼承,只能實現(xiàn)接口。同時,線程池也是非常高效的,很容易實現(xiàn)和適用。
舉例:
例1:
public class ThreadDemo {public static void main(String[] args) {Runnable task = () -> {try {for(int i = 5; i > 0; i--) {System.out.println("Child Thread: " + i);Thread.sleep(100);}} catch (Exception e) {}System.out.println("child thread exit.");};Thread t1 = new Thread(task);System.out.println("Child Thread: " + t1);t1.start(); try {for(int i = 5; i > 0; i--) {System.out.println("Main Thread: " + i);Thread.sleep(100);}} catch (Exception e) {}System.out.println("Main thread exit.");} }例2:
public class ExecutorsTest {public static void main(String[] args) {ExecutorService executor = Executors.newSingleThreadExecutor();Future<String> ft = executor.submit(() -> {System.out.println("Hello Thread!");return "sucess";});try {System.out.println("return : " + ft.get());} catch (Exception e) {e.printStackTrace();}executor.shutdown();} }希望對各位正在準備面試的小伙伴有所幫助!
《JAVA面試機經(jīng)基礎(chǔ)篇》 郭屹老師著百度搜索JAVA面試機經(jīng)基礎(chǔ)篇即可
歡迎搜索關(guān)注公眾號 爪哇河谷
或添加我的微信 領(lǐng)取更多干貨
總結(jié)
以上是生活随笔為你收集整理的创建线程的方式_创建线程有几种不同的方式?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机音乐奔跑,跑起来!100首最适合跑
- 下一篇: Oracle订单号就是授权号码,orac