线程创建的四种方式

1.继承Thread:很少使用,因为java单继承的原因

public class ExtendsThread extends Thread{
    @Override
    public void run() {
        System.out.println("线程创建,在这里写代码");
    }

    public static void main(String[] args) {
        Thread t1 = new ExtendsThread();
        t1.start();
    }
}

2.实现Runnable接口:解决的java单继承的局限

public class ImplRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("线程创建,在这里写代码");
    }

    public static void main(String[] args) {
        Runnable runnable = new ImplRunnable();
        Thread t1 = new Thread(runnable);
        t1.start();
    }
}

3.实现Callable接口:拥有返回值,也能抛出异常

public class ImplCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("线程创建,在这里写代码");
        return 1024;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new ImplCallable());

        Thread t1 = new Thread(futureTask);
        t1.start();

        //获取返回值,但这方法会阻塞
        System.out.println(futureTask.get()); //1024

    }
}

4.线程池:复用线程,控制最大并发数,管理线程

public class ThreadPool {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(1); //创建固定大小线程池
//ExecutorService executorService = Executors.newCachedThreadPool();创建不定大小线程池,最大为Integer.MAX_VALUE
//ExecutorService executorService = Executors.newSingleThreadExecutor();创建大小为1的线程池

        try{
            threadPool.execute(() -> {
                System.out.println("线程创建,在这里写代码");
            });
        } finally {
            threadPool.shutdown();
        }
    }

}

但阿里巴巴编程规范里,指出这中创建方式会出现错误,所以我们一般是通过ThreadPoolExecutor自定义线程池

 

public class MyThreadPool {

    public static void main(String[] args) {
        // 声明了一个
        // 核心线程数为2
        // 最大线程数为5
        // 空闲线程存活时间 1s
        // 阻塞队列采用LinkedBlockingQueue并限制其大小为3
        // 拒绝策略为CallerRunsPolicy ---拒绝策略有四种,可以自己去详细了解下
        // 的线程池。
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5, 1L,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(3),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());

        try{
            threadPool.execute(() -> {
                System.out.println("线程创建,在这里写代码");
            });
        } finally {
            threadPool.shutdown();
        }
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值