日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

四种方式下创建线程启动的区别

發布時間:2024/4/13 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 四种方式下创建线程启动的区别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
  • 繼承Thread類,重寫run方法
  • 實現Runnable接口,重寫run方法
  • 實現Callable接口,配合FutureTask來實現返回值,重寫call方法
  • 創建一個線程池,通過線程池調度
    我們來看下代碼:
import java.util.concurrent.*; public class ThreadTest {public static ExecutorService executor = Executors.newFixedThreadPool(10);public static void main(String[] args) throws ExecutionException, InterruptedException {// System.out.println("main......start.....");// 1、通過繼承Thread類// Thread thread = new Thread01();// thread.start();// System.out.println("main......end.....");// 2、通過實現Runnable接口// Runable01 runable01 = new Runable01();// new Thread(runable01).start();// 3、通過FutureTask傳參Callable,實現有返回值// FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());// new Thread(futureTask).start();// System.out.println(futureTask.get());// service.execute(new Runable01());System.out.println("main......start.....");} public static class Thread01 extends Thread {@Overridepublic void run() {System.out.println("當前線程:" + Thread.currentThread().getId());int i = 10 / 2;System.out.println("運行結果:" + i);}}public static class Runable01 implements Runnable {@Overridepublic void run() {System.out.println("當前線程:" + Thread.currentThread().getId());int i = 10 / 2;System.out.println("運行結果:" + i);}}public static class Callable01 implements Callable<Integer> {@Overridepublic Integer call() throws Exception {System.out.println("當前線程:" + Thread.currentThread().getId());int i = 10 / 2;System.out.println("運行結果:" + i);return i;}} }

第一種和第二種都是無返回值的創建線程執行任務,第三種是有返回值的創建線程執行任務。
以上這三種創建線程的方式在業務中是不能出現的,因為它們的創建線程和銷毀線程是非常消耗時間的,影響業務的響應時間,拋開這些不講,它也非常的消耗資源,假設我現在有10萬的并發請求打過來,如果我用以上三種的其中一種創建線程執行任務的話,理想狀態下是需要創建10萬個線程,這是不可能的,在期間肯定會造成內存爆了,服務器宕機的。

?

總結

以上是生活随笔為你收集整理的四种方式下创建线程启动的区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。