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

詳解Java實(shí)現(xiàn)多線(xiàn)程的三種方式

 更新時(shí)間:2016年03月27日 11:04:20   作者:趙杰A-124  
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)多線(xiàn)程的三種方式,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Java實(shí)現(xiàn)多線(xiàn)程的三種方式,供大家參考,具體內(nèi)容如下

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();
    }
  }

}

方法一,繼承自Thread

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

run方法為線(xiàn)程執(zhí)行體,ThreadExtendsThread對(duì)象即為線(xiàn)程對(duì)象。

方法二,實(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方法為線(xiàn)程執(zhí)行體,使用時(shí)New一個(gè)Thread對(duì)象,Runnable對(duì)象作為target傳遞給Thread對(duì)象。且同一個(gè)Runnable對(duì)象可作為多個(gè)Thread的target,這些線(xiàn)程均共享Runnable對(duì)象的實(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接口類(lèi)似于Runnable接口,但比對(duì)方強(qiáng)大,線(xiàn)程執(zhí)行體為call方法,該方法具有返回值和可拋出異常。使用時(shí)將Callable對(duì)象包裝為FutureTask對(duì)象,通過(guò)泛型指定返回值類(lèi)型??缮院蛘{(diào)用FutureTask的get方法取回執(zhí)行結(jié)果。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論