开启线程的四种方式

开启线程四种方式

public class ThreadTest {
    // 开启一个线程池,容量为10
    public static ExecutorService executorService = Executors.newFixedThreadPool(10);
    public static void main(String[] args) {
        // 1.继承thread
        MyThread myThread = new MyThread();
        myThread.start();

        // 2.实现runnable
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();

        // 3.实现callable + FutureTask  futuretask最后也是实现runnable
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        Thread thread1 = new Thread(futureTask);
        thread1.start();

        // 4.给线程池直接提交任务
        executorService.submit(new MyRunnable());

    }

    // 1.继承thread
    public static class MyThread extends Thread{
        @Override
        public void run() {
            System.out.println("开始执行线程:"+ Thread.currentThread().getName());
            System.out.println("继承thread");
            System.out.println("线程执行结束");
        }
    }

    // 2.实现runnable接口
    public static class MyRunnable implements Runnable{
        @Override
        public void run() {
            System.out.println("开始执行线程:"+ Thread.currentThread().getName());
            System.out.println("实现runnable");
            System.out.println("结束线程");
        }
    }

    // 3.实现Callable接口 + FutureTask
    public static class MyCallable implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            System.out.println("开始执行线程:" + Thread.currentThread().getName());
            System.out.println("实现callable");
            int a = 10/5;
            return a;
        }
    }

}

四种方式的特点

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值