【P说】Java三种启动线程的方法

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

/**
 * @author Chris Wu
 * @date 2020/5/9 9:49
 */
public class ThreeThreadMethod {
    //继承Thread
    //优点:可以在方法中通过this调用Thread的方法
    //缺点:可拓展性差,因为java是单继承的
    static class Thread1 extends Thread {
        @Override
        public void run() {
            System.out.println("继承Thread类");
            //可以直接通过this调用Thread的方法
            this.isInterrupted();
        }
    }

    //实现Runnable接口
    //优点:有很好的拓展性
    //缺点:无法通过this调用Thread的方法,必须先获取当前线程Thread.currentThread()
    static class Thread2 implements Runnable {

        public void run() {
            System.out.println("实现Runnable接口");
            //无法直接通过this调用Thread的方法
            Thread.currentThread().isInterrupted();
        }
    }

    //实现callable接口,泛型为返回值的类型
    //可以取得返回值的Runnable
    static class Thread3 implements Callable<String> {

        public String call() throws Exception {
            System.out.println("实现Callable接口");
            //无法直接通过this调用Thread的方法
            Thread.currentThread().isInterrupted();
            return "implements Callable";
        }
    }

    public static void main(String[] args) {
        //使用继承了Thread类的类来启动线程
        Thread1 thread1 = new Thread1();
        thread1.start();

        //使用实现Runnable接口的类来启动线程
        Thread2 thread2 = new Thread2();
        new Thread(thread2).start();

        //使用实现Callable接口的类来启动线程
        Thread3 thread3 = new Thread3();
        //由于Thread接受实现runnable接口的类,所以要把实现Callable接口的类进行包装,FutureTask实现Runnable接口
        FutureTask<String> futureTask = new FutureTask<String>(thread3);
        new Thread(futureTask).start();
        try {
            //通过FutureTask的get方法可以拿到线程操作结果的返回值,get是一个阻塞方法
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值