java创建线程的三种方式及其对比

一、继承Thread类创建线程类

(1)定义Thread类的子类,并重写该类的run方法,该run方法的方法体就代表了线程要完成的任务。因此把run()方法称为执行体。

(2)创建Thread子类的实例,即创建了线程对象。

(3)调用线程对象的start()方法来启动该线程。

public class Main {            
      public static void main(String[] args) throws Exception {     
          myThread th1 = new myThread();
          myThread th2 = new myThread();
          th1.start();
          th2.start();
     }           
}

class myThread extends Thread {    
    public void run() {
        for(int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "运行 : " + i );
        }
    }
}

二、通过Runnable接口创建线程类

(1)定义runnable接口的实现类,并重写该接口的run()方法,该run()方法的方法体同样是该线程的线程执行体。

(2)创建 Runnable实现类的实例,并依此实例作为Thread的target来创建Thread对象,该Thread对象才是真正的线程对象。

(3)调用线程对象的start()方法来启动该线程。

事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run(),参考JDK源代码:
public void run() {
  if (target != null) {
   target.run();
  }
}

示例代码为:

public class Main {            
      public static void main(String[] args) throws Exception {   
          myThread myth = new myThread();
          Thread th1 = new Thread(myth);
          Thread th2 = new Thread(myth);
          th1.start();
          th2.start();
     }           
}

class myThread implements Runnable {
    
    public void run() {
        for(int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "运行 : " + i );
        }
    }
}

三、通过Callable和Future创建线程

(1)创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。

(2)创建实现了Callable接口的实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。

(3)使用FutureTask对象作为Thread对象的target创建并启动新线程。

(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值

实例代码:

package test4;

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

public class Main {

    public static void main(String[] args) {
        ThreadDemo td = new ThreadDemo();

        // 1.执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果
        FutureTask<Integer> result = new FutureTask<>(td);
        new Thread(result).start();

        // 2.接收线程运算后的结果
        Integer sum;
        try {
            //等所有线程执行完,获取值,因此FutureTask 可用于 闭锁
            sum = result.get();
            System.out.println("-----------------------------");
            System.out.println(sum);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
} 
class ThreadDemo implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= 10; i++) {
            System.out.println(i);
            sum += i;
        }
        return sum;
    }
}

结果

0
1
2
3
4
5
6
7
8
9
10
-----------------------------
55

四、创建线程的三种方式的对比

原文地址:https://www.cnblogs.com/chengdabelief/p/7235959.html