并发编程(2)—— 创建线程的方式

该博客聚焦Java并发编程,介绍了创建线程的三种方式,分别是继承Thread类、实现Runnable接口以及实现Callable接口并配合FutureTask,还给出了每种方式的运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇:并发编程(1)—— 基础概念

创建线程的方式

  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口,配合FutureTask

一、继承Thread类

public class NewThred  {

    public static void main(String[] args) {
        Thread testThread = new TestThread();
        testThread.setName("The testThread's name thread");
        testThread.start();
    }

    public static class TestThread extends Thread{
        @Override
        public void run(){
            System.out.printf(Thread.currentThread().getName());
        }
    }
}

运行结果:

 The testThread's name thread

二、实现Runnable接口

public class NewThred  {

    public static void main(String[] args) {
        Thread testRunnable = new Thread(new TestRunnable());
        testRunnable.setName("The testRunnable's name runnable");
        testRunnable.start();
    }

    public static class TestRunnable implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }
}

运行结果:

The testRunnable's name runnable

三、实现Callable,配合使用FutureTask

public class NewThred  {

    public static void main(String[] args) {
        Callable<String> testCallable = new TestCallable();
        FutureTask<String> futureTask = new FutureTask<>(testCallable);
        Thread thred = new Thread(futureTask);
        thred.setName("The testCallable's name callable");
        thred.start();
        
        try {
            System.out.printf("返回值:"+futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static class TestCallable implements Callable<String>{
        @Override
        public String call() throws Exception {
            System.out.println(Thread.currentThread().getName());
            return Thread.currentThread().getName();
        }
    }
}

运行结果:

The testCallable's name callable
返回值:The testCallable's name callable

下一篇:并发编程(3)——interrupt()中断线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值