创建线程的5种方式(匿名内部类、lambda表达式版)

目录

使用Thread匿名内部类创建

使用Runnable创建

使用Runnable的lambda表达式

 使用Callable搭配FutureTask(Lambda表达式)

使用Thread匿名内部类创建

指定线程的名称为t1

        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                super.run();
            }
        };
        t1.start();

使用Runnable创建

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
            }
        };
        Thread t1 = new Thread(runnable, "t1");
        t1.start();

使用Runnable的lambda表达式

Runnable是一个函数式接口,因此可以通过lambda表达式

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

 创建线程

        Thread t2=new Thread(()->{
            while(true) {
                System.out.println("lele");
            }
            },"t1");
        t2.start();

 使用Callable搭配FutureTask(Lambda表达式)

大家应该理解Lambda表达式了吧

可以点击alt+enter将匿名内部类替换为Lambda,也可以再次点击alt+enter转换回来

 

Callable搭配FutureTask可以获取结果的返回值,调用FutureTask实例的get()方法同步模式

如果不调用get()方法的话就是异步

Callable是一个函数式接口,因此可以使用Lambda表达式

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

通过FutureTask的构造方法创建对象

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

 

        Thread t1 = new Thread(runnable, "t1");
        t1.start();

        Thread t2=new Thread(()->{
            while(true) {
                System.out.println("lele");
            }
            },"t1");
        t2.start();

        FutureTask task = new FutureTask<Integer>(()->{
            System.out.println("乐乐");
            return 1;
        });
        Thread t3 = new Thread(task,"t3");
        t3.start();
        //等待获取
        System.out.println(task.get());
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值