溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java多線程中創(chuàng)建線程的方法有哪些

發(fā)布時間:2021-06-07 13:07:22 來源:億速云 閱讀:174 作者:小新 欄目:編程語言

這篇文章主要介紹Java多線程中創(chuàng)建線程的方法有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

1.實現(xiàn)Runnable接口,重載run(),無返回值

package thread;
 
public class ThreadRunnable implements Runnable {
  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread().getName() + ":" + i);
    }
  }
}
 
 
package thread;
 
public class ThreadMain {
  public static void main(String[] args) throws Exception {
    ThreadRunnable threadRunnable1 = new ThreadRunnable();
    ThreadRunnable threadRunnable2 = new ThreadRunnable();
    ThreadRunnable threadRunnable3 = new ThreadRunnable();
    ThreadRunnable threadRunnable4 = new ThreadRunnable();
    Thread thread1 = new Thread(threadRunnable1);
    Thread thread2 = new Thread(threadRunnable2);
    Thread thread3 = new Thread(threadRunnable3);
    Thread thread4 = new Thread(threadRunnable4);
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
  }
}

2.繼承Thread類,復寫run()

使用時通過調用Thread的start()(該方法是native),再調用創(chuàng)建線程的run(),不同線程的run方法里面的代碼交替執(zhí)行。

不足:由于java為單繼承,若使用線程類已經有個父類,則不能使用該方式創(chuàng)建線程。

public class ThreadEx extends Thread {
  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread() + ":" + i);
    }
  }
}
 
 
public class ThreadMain {
  public static void main(String[] args)
  {
    ThreadEx threadEx = new ThreadEx();
    threadEx.start();
  }
}

3.實現(xiàn)Callable接口,通過FutureTask/Future來創(chuàng)建有返回值的Thread線程,通過Executor執(zhí)行

補充:與實現(xiàn)Runnable接口類似,都是實現(xiàn)接口,不同的是該方式有返回值,可以獲得異步執(zhí)行的結果。

延伸:FutureTask是類,F(xiàn)uture是接口。

package thread;
 
import java.util.concurrent.*;
 
public class ThreadCallable {
  public static void main(String[] args) throws Exception {
    FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
      public Integer call() throws Exception {
        for (int i = 0; i < 10; i++) {
          System.out.println(Thread.currentThread().getName() + ":" + i);
        }
        return 1;
      }
    });
    Executor executor = Executors.newFixedThreadPool(1);
    ((ExecutorService) executor).submit(futureTask);
 
    //獲得線程執(zhí)行狀態(tài)
    System.out.println(Thread.currentThread().getName() + ":" + futureTask.get());
  }
}

4.使用Executors創(chuàng)建ExecutorService,入?yún)allable或Future

補充:適用于線程池和并發(fā)

package thread;
 
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
 
import static java.lang.Thread.sleep;
 
public class ThreadExecutors {
  private final String threadName;
 
  public ThreadExecutors(String threadName) {
    this.threadName = threadName;
  }
 
  private ThreadFactory createThread() {
    ThreadFactory tf = new ThreadFactory() {
      public Thread newThread(Runnable r) {
        Thread thread = new Thread();
        thread.setName(threadName);
        thread.setDaemon(true);
        try {
          sleep(1000);
        }
        catch (InterruptedException e) {
          e.printStackTrace();
        }
        return thread;
      }
    };
    return tf;
  }
 
  public Object runCallable(Callable callable) {
    return Executors.newSingleThreadExecutor(createThread()).submit(callable);
  }
 
  public Object runFunture(Runnable runnable) {
    return Executors.newSingleThreadExecutor(createThread()).submit(runnable);
  }
}
 
 
 
package thread;
 
import java.util.concurrent.*;
 
public class ThreadMain {
  public static void main(String[] args) throws Exception {
    ThreadExecutors threadExecutors = new ThreadExecutors("callableThread");
    threadExecutors.runCallable(new Callable() {
      public String call() throws Exception {
        return "success";
      }
    });
 
    threadExecutors.runFunture(new Runnable() {
      public void run() {
        System.out.println("execute runnable thread.");
      }
    });
  }
}

5 Runnable接口和Callable接口區(qū)別

  1. 1)兩個接口需要實現(xiàn)的方法名不一樣,Runnable需要實現(xiàn)的方法為run(),Callable需要實現(xiàn)的方法為call()。

  2. 2)實現(xiàn)的方法返回值不一樣,Runnable任務執(zhí)行后無返回值,Callable任務執(zhí)行后可以得到異步計算的結果。

  3. 3)拋出異常不一樣,Runnable不可以拋出異常,Callable可以拋出異常。

6 Callable返回值意義在哪兒,不要返回值可以嗎,什么時候需要用到返回值?

首先Callable是線程異步執(zhí)行的結果狀態(tài),如果有兩個線程A和B,B中的某個業(yè)務邏輯中需要確定A結束后才能進行,那么就需要獲得線程A的執(zhí)行結果。

設計背景:一個任務需要進行一系列操作,比如拷貝大量的基礎數(shù)據(jù),以及解析數(shù)據(jù),并入庫,由于數(shù)量大,整個過程需要持續(xù)十秒左右,用戶體驗差,需要降低到2~5s。

設計思路:經過分解過程,將拷貝數(shù)據(jù)分為一個過程,同時涵蓋部分解析數(shù)據(jù)功能,剩下解析數(shù)據(jù)劃為一個過程,兩個過程異步執(zhí)行,其中最后一個任務狀態(tài)入庫時需要將所有業(yè)務操作都執(zhí)行完成后更新,此時就需要用到線程中的返回值。

以上是“Java多線程中創(chuàng)建線程的方法有哪些”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI