欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java 實(shí)現(xiàn)多線程的幾種方式匯總

 更新時(shí)間:2016年03月21日 10:56:34   投稿:hebedich  
JAVA多線程實(shí)現(xiàn)方式主要有三種:繼承Thread類、實(shí)現(xiàn)Runnable接口、使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的多線程。其中前兩種方式線程執(zhí)行完后都沒有返回值,只有最后一種是帶返回值的。

我們先來看段示例代碼

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Main {

  public static void main(String[] args) {
    //方法一:繼承Thread
    int i = 0;
//    for(; i < 100; i++){
//      System.out.println(Thread.currentThread().getName() + " " + i);
//      if (i == 5) {
//        ThreadExtendsThread threadExtendsThread = new ThreadExtendsThread();
//        threadExtendsThread.start();
//      }
//    }
    
    //方法二:實(shí)現(xiàn)Runnable
//    for(i = 0; i < 100; i++){
//      System.out.println(Thread.currentThread().getName() + " " + i);
//      if (i == 5) {
//        Runnable runnable = new ThreadImplementsRunnable();
//        new Thread(runnable).start();
//        new Thread(runnable).start();
//      }
//    }

    //方法三:實(shí)現(xiàn)Callable接口
    Callable<Integer> callable = new ThreadImplementsCallable();
    FutureTask<Integer> futureTask = new FutureTask<>(callable);
    for(i = 0; i < 100; i++){
      System.out.println(Thread.currentThread().getName() + " " + i);
      if (i == 5) {
        new Thread(futureTask).start();
        new Thread(futureTask).start();
      }
    }
    try {
      System.out.println("futureTask ruturn: " + futureTask.get());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

接下來我們來詳細(xì)探討下Java 實(shí)現(xiàn)多線程的幾種方式

方法一,繼承自Thread

public class ThreadExtendsThread extends Thread {
  private int i;
  @Override
  public void run() {
    for(; i < 100; i++) {
      System.out.println(getName() + " " + i); 
    }
  }
}

run方法為線程執(zhí)行體,ThreadExtendsThread對象即為線程對象。

方法二,實(shí)現(xiàn)Runnable接口

public class ThreadImplementsRunnable implements Runnable {
  private int i;
  @Override
  public void run() {
    for(; i < 100; i++){
      System.out.println(Thread.currentThread().getName() + " " + i);
    }
  }
}

run方法為線程執(zhí)行體,使用時(shí)New一個(gè)Thread對象,Runnable對象作為target傳遞給Thread對象。且同一個(gè)Runnable對象可作為多個(gè)Thread的target,這些線程均共享Runnable對象的實(shí)例變量。

方法三,實(shí)現(xiàn)Callable接口

import java.util.concurrent.Callable;

public class ThreadImplementsCallable implements Callable<Integer> {
  private int i;
  
  @Override
  public Integer call() throws Exception {
    for(; i < 100; i++){
      System.out.println(Thread.currentThread().getName() + " " + i);
    }
    return i;
  }
}

Callable接口類似于Runnable接口,但比對方強(qiáng)大,線程執(zhí)行體為call方法,該方法具有返回值和可拋出異常。使用時(shí)將Callable對象包裝為FutureTask對象,通過泛型指定返回值類型??缮院蛘{(diào)用FutureTask的get方法取回執(zhí)行結(jié)果。

相關(guān)文章

最新評論