并发编程(二):创建线程方法

💗一. 创建和运行线程 💗

方法一,直接使用 Thread

public class test01 {
    public static void main(String[] args) {
        // 构造方法的参数是给线程指定名字
        Thread thread = new Thread("t1") {
            // 重写的run方法内实现了要执行的代码
            @Override
            public void run() {
                // 要执行的任务
                log.debug("hello,world!");
            }
        };
        // 启动线程
        thread.start();
    }
}

控制台输出 :17:38:50.515 [t1] DEBUG thread01.test01 - hello,world!

方法二,使用 Runnable 配合 Thread

public class test01 {
    public static void main(String[] args) {
        // 创建任务对象
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                log.debug("hello,world!");
            }
        };

// 参数1 是任务对象; 参数2 是线程名字
        Thread t2 = new Thread(runnable, "t2");
        t2.start();
    }
}

控制台输出 :17:43:23.974 [t2] DEBUG thread01.test01 - hello,world!

JDK8 以后可以使用 lambda表达式

 // 创建任务对象
        Runnable runnable = () -> log.debug("hello,world!");

// 参数1 是任务对象; 参数2 是线程名字
        Thread t2 = new Thread(runnable, "t2");
        t2.start();

原理之 Thread 与 Runnable 的关系

方式二是重写了Runnable 接口中的run方法,

 

 然后又将Runnable 对象传到Thread 类中调用run方法,

 方式一是直接重写了Thread 类中的run方法

方法三,FutureTask 配合 Thread

public class test03 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 创建任务对象,<>里是泛型,这里就定义为String
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "测试";
            }
        };
        //同样<>里是泛型,这里就定义为String
        FutureTask<String> futureTask = new FutureTask<>(callable);
        // 参数1 是任务对象; 参数2 是线程名字
        new Thread(futureTask, "t3").start();

        // 获取结果
        String result = futureTask.get();
        log.debug("结果是:{}", result);
    }
}

控制台输出 : 19:43:45.383 [main] DEBUG thread01.test03 - 结果是:测试

可以看到,在Callable接口中的call方法是有一个泛型的返回值的,而且可以抛出异常,而Runnable中的run方法是不能抛异常的;

 FutureTask类是实现了一个叫RunnableFuture的接口

 而RunnableFuture里面其实是继承了Runnable接口的;

此外还继承了一个Future接口;它里面就有获取返回的执行结果的get方法,而run方法是没有返回结果的,是void

 

以上就是我总结的一些创建线程的一些方式,在这里先不涉及线程池,线程池以后会单独介绍一下~

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值