Java 并發(fā)編程中如何創(chuàng)建線程
線程是基本的調(diào)度單位,它被包含在進(jìn)程之中,是進(jìn)程中的實(shí)際運(yùn)作單位,它本身是不會(huì)獨(dú)立存在。一個(gè)進(jìn)程至少有一個(gè)線程,進(jìn)程中的多個(gè)線程共享進(jìn)程的資源。
Java中創(chuàng)建線程的方式有多種如繼承Thread類(lèi)、實(shí)現(xiàn)Runnable接口、實(shí)現(xiàn)Callable接口以及使用線程池的方式,線程池將在后面文章中單獨(dú)介紹,這里先介紹另外三種方式。
繼承Thread類(lèi)優(yōu)點(diǎn):在run方法里可以用this獲取到當(dāng)前線程。
缺點(diǎn):由于Java不支持多繼承,所以如果繼承了Thread類(lèi)后就不能再繼承其他類(lèi)。
public class MyThread extends Thread { /** * 線程要執(zhí)行的任務(wù) */ @Override public void run() { System.out.println('do something...'); } public static void main(String[] args) {//創(chuàng)建線程 MyThread myThread = new MyThread();//啟動(dòng)線程 myThread.start(); }}實(shí)現(xiàn)Runnable接口
優(yōu)點(diǎn):實(shí)現(xiàn)Runnable接口后不影響繼承其他類(lèi),以及有利于多個(gè)線程資源共享。
缺點(diǎn):獲取當(dāng)前線程需要調(diào)用Thread.currentThread()。
public class MyThread implements Runnable { /** * 線程要執(zhí)行的任務(wù) */ @Override public void run() { System.out.println('do something...'); } public static void main(String[] args) {//創(chuàng)建兩個(gè)線程,并指定相同的任務(wù)Thread thread1 = new Thread(new MyThread()); Thread thread2 = new Thread(new MyThread());//啟動(dòng)線程 thread1.start(); thread2.start(); }}實(shí)現(xiàn)Callable接口
優(yōu)缺點(diǎn)類(lèi)似于實(shí)現(xiàn)Runnable接口,但是實(shí)現(xiàn)Callable接口可以有返回值。
public class MyThread implements Callable<String> { /** * 線程要執(zhí)行的任務(wù),并且具有返回值 */ @Override public String call() throws Exception { System.out.println('do something...'); Thread.sleep(3000); return '我是返回值'; } public static void main(String[] args) throws ExecutionException, InterruptedException {//創(chuàng)建異步任務(wù) FutureTask<String> futureTask = new FutureTask(new MyThread());//啟動(dòng)線程 new Thread(futureTask).start();//阻塞等待線程執(zhí)行完成并返回結(jié)果 String result = futureTask.get(); System.out.println(result); }}
以上就是Java 并發(fā)編程中如何創(chuàng)建線程的詳細(xì)內(nèi)容,更多關(guān)于Java 創(chuàng)建線程的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 用Spring JMS使異步消息變得簡(jiǎn)單2. PHP驗(yàn)證碼工具-Securimage3. 關(guān)于IDEA 2020.3 多窗口視圖丟失的問(wèn)題4. js實(shí)現(xiàn)碰撞檢測(cè)5. 一文帶你徹底理解Java序列化和反序列化6. JS實(shí)現(xiàn)前端動(dòng)態(tài)分頁(yè)碼代碼實(shí)例7. PHP使用Swagger生成好看的API文檔8. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條9. Python 下載Bing壁紙的示例10. Python 制作查詢(xún)商品歷史價(jià)格的小工具

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