线程创建的五种方式

方式1:

继承Thread,重写run方法,直接new对象.start启动

public class T1 {
    static class MyThread extends Thread{
        @Override
        public void run() {
            System.out.println("MyThread...");
        }
    }

    public static void main(String[] args) {
        new MyThread().start();
    }
}

方式2:

实现Runnable接口,重写run方法,new出Thread传入对象作为参数,.start启动

public class T2 {
    static class MyRun implements Runnable{
        public void run() {
            System.out.println("MyRun...");
        }
    }

    public static void main(String[] args) {
        new Thread(new MyRun()).start();
    }
}

方式3:

new出Tread对象,使用lambda表达式,.start启动

public class T3 {
    public static void main(String[] args) {
        new Thread(()-> System.out.println("lambda...")).start();
    }
}

方式4:

使用线程池ExecutorService,调用execute方法,传入一个Runnable的实现类

public class T4 {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(() -> System.out.println("Executor..."));
        service.shutdown();
    }
}


方式5:

实现Callable接口,用线程池的submit方法调用
返回值为Future,指定泛型作为线程的返回值类型
不用线程池的情况下,需要用FutureTask套一层作为参数传给Thread

public class T5 {
    static class MyCall implements Callable<String> {
        @Override
        public String call(){
            return "Callable...";
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();

        Future<String> submit = service.submit(new MyCall());
        System.out.println(submit.get());

        service.shutdown();

        FutureTask task = new FutureTask(new MyCall());
        new Thread(task).start();
    }
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值