线程创建的四种方式

import java.util.concurrent.*;

class Mythread1 extends Thread{
    @Override
    public void run(){
        System.out.println("通过继承Thread类"+Thread.currentThread().getName());
    }
}
class Mythread2 implements Runnable{
    @Override
    public void run() {
        System.out.println("通过实现Runnable接口,不会返回结果或抛出异常");
    }
}
class Mythread3 implements Callable{
    @Override
    public String call() throws Exception {
        System.out.println("通过实现Callable接口,会返回结果或抛出异常");
        return "Callable返回的结果";
    }
}

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService ex = new ThreadPoolExecutor(5,10,1,TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                new ThreadPoolExecutor.CallerRunsPolicy());
        //Thread()要求传入一个Runnable类型的变量
        new Mythread1().start();
        new Thread(new Mythread2());
        new Thread(new FutureTask<String>(new Mythread3()));
        ex.execute(new Mythread2());
        Future<String> submit = ex.submit(new Mythread3());
        System.out.println(submit.get());

        for(int i = 0;i<10;i++){
            ex.execute(new Mythread1());
        }
        ex.shutdown();
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值