创建线程的四种方式(继承Thread/实现Runnable/Callable+线程池)

创建线程的4种方式

一、继承Thread类

public class Main {
    public static void main(String[] args) {
//        // 1.创建Thread子类对象
//        ThreadDemo threadDemo = new ThreadDemo();
//        // 2.启动线程
//        threadDemo.start();
        // 使用内部类方式
        new Thread() {
            @Override
            public void run() {
                System.out.println("继承Thread来创建线程:" + Thread.currentThread().getName());
            }
        }.start();
    }

    static class ThreadDemo extends Thread {
        @Override
        public void run() {
            System.out.println("继承Thread来创建线程:" + Thread.currentThread().getName());
        }
    }
}

二、实现Runnable接口

public class Main {
    public static void main(String[] args) {
//        // 1.创建Runnable实现类对象
//        ThreadDemo threadDemo = new ThreadDemo();
//        // 2.创建Thread对象
//        Thread thread = new Thread(threadDemo);
//        // 3.启动线程
//        thread.start();
        // 使用内部类方式
        new Thread(new Runnable() {
            public void run() {
                System.out.println("实现Runnable来创建线程:" + Thread.currentThread().getName());
            }
        }).start();
    }

    static class ThreadDemo implements Runnable {
        public void run() {
            System.out.println("实现Runnable来创建线程:" + Thread.currentThread().getName());
        }
    }
}

三、实现Callable接口

public class Main {
    public static void main(String[] args) {
        // 1.创建Callable实现对象
        ThreadDemo threadDemo = new ThreadDemo();
        // 2.创建FutureTask对象
        FutureTask<String> futureTask = new FutureTask<String>(threadDemo);
        // 3.创建Thread对象
        Thread thread = new Thread(futureTask);
        // 4.启动线程
        thread.start();
        // 获取线程返回值
        try {
            String callReturn = futureTask.get(); // 会一直等待线程结束获取其返回值,如果线程被中断会抛异常
            System.out.println(callReturn);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    static class ThreadDemo implements Callable<String> {
        public String call() throws Exception {
            return "实现Callable接口创建线程:" + Thread.currentThread().getName();
        }
    }
}

四、使用Executor框架来创建线程池

public class Main {
    public static void main(String[] args) {
        // 方式1.Executors创建单个线程池
//        ExecutorService pool = Executors.newSingleThreadExecutor();
//        pool.execute(new Runnable() {
//            public void run() {
//                System.out.println("线程池创建线程:" + Thread.currentThread().getName());
//            }
//        });
//        pool.shutdown();
        // 方式2.Executors创建固定数量线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        List<Future<String>> futures = new ArrayList<Future<String>>(); // 存储结果集
        for(int i = 0; i < 5; i++) {
            Future<String> submit = pool.submit(new Callable<String>() {
                public String call() throws Exception {
                    return "线程池创建线程:" + Thread.currentThread().getName();
                }
            });
            futures.add(submit);
        }

        System.out.println("开始获取任务结果");
        for(Future<String> future : futures) {
            try {
                // 使用get(long timeout, TimeUnit unit)指定获取结果超时时间
                System.out.println(future.get(1000, TimeUnit.SECONDS));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
        System.out.println("获取任务结果结束");
        // 关闭线程池
        pool.shutdown();
    }
}

执行结果:
开始获取任务结果
线程池创建线程:pool-1-thread-1
线程池创建线程:pool-1-thread-2
线程池创建线程:pool-1-thread-3
线程池创建线程:pool-1-thread-4
线程池创建线程:pool-1-thread-5
获取任务结果结束

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值