首页 > 编程 > Java > 正文

Java 实现多线程的几种方式汇总

2019-11-26 14:29:25
字体:
来源:转载
供稿:网友

我们先来看段示例代码

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();//      }//    }        //方法二:实现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();//      }//    }    //方法三:实现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();    }  }}

接下来我们来详细探讨下Java 实现多线程的几种方式

方法一,继承自Thread

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

run方法为线程执行体,ThreadExtendsThread对象即为线程对象。

方法二,实现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方法为线程执行体,使用时New一个Thread对象,Runnable对象作为target传递给Thread对象。且同一个Runnable对象可作为多个Thread的target,这些线程均共享Runnable对象的实例变量。

方法三,实现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接口,但比对方强大,线程执行体为call方法,该方法具有返回值和可抛出异常。使用时将Callable对象包装为FutureTask对象,通过泛型指定返回值类型。可稍候调用FutureTask的get方法取回执行结果。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表