异步任务——多线程

初始化线程的4种方式:

1、继承Thread

public class TestThread extends Thread {
    @Override
    public void run() {
        System.out.println("当前线程:" + Thread.currentThread().getName());
        int i = 10 / 2;
        System.out.println("运行结果:" + i);
    }
    public static void main(String[] args) {
        System.out.println("main start");
        TestThread testThread = new TestThread();
        //启动线程
        testThread.start();
        System.out.println("main end");
    }
}

main start
main end
当前线程:Thread-0
运行结果:5

2、实现Runnable接口

public class TestThread2 implements  Runnable{
    public void run() {
        System.out.println("当前线程:" + Thread.currentThread().getName());
        int i = 10 / 2;
        System.out.println("运行结果:" + i);
    }
    public static void main(String[] args) {
        System.out.println("main start");
        TestThread2 testThread = new TestThread2();
        //启动线程
        new Thread(testThread).start();
        System.out.println("main end");
    }
}

main start
main end
当前线程:Thread-0
运行结果:5
实际上Thread类也是实现了Runnable接口

3、实现Callable接口+FutureTask(可以得到返回结果 ,可以处理异常,jdk1.5以后提供)

public class TestThread3 implements Callable<Integer> {
    public Integer call() throws Exception {
        System.out.println("当前线程:" + Thread.currentThread().getName());
        int i = 10 / 2;
        System.out.println("运行结果:" + i);
        return i;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main start");
        FutureTask<Integer> futureTask = new FutureTask<>(new TestThread3());
        new Thread(futureTask).start();
        //阻塞等待整个线程执行完成,获取返回结果
        Integer result = futureTask.get();
        System.out.println("返回结果:"+result);
        System.out.println("main end");
    }
}

main start
当前线程:Thread-0
运行结果:5
返回结果:5
main end 因为要阻塞等待线程返回结果,所以主线程最后才结束

在业务代码里面,以上三种启动线程的方式都不用,应该将所有的异步任务都交给线程池执行

4、线程池

创建简单线程池的4种方式:
ExecutorService service = Executors.newFixedThreadPool();
该方法返回一个固定线程数量的线程池。该线程池中线程数量始终 不变。当有一个新的任务提交时,线程池中若有空闲线程,则立即执行。若没有,则新的任务会被暂存在一个任务队列中,待有线程空闲时,便处理任务队列中的任务。
缺点:它会创建一个Integer.MAX_VALUE长度的阻塞队列。
ExecutorService service1 = Executors.newSingleThreadExecutor();
创建一个单线程的线程池,它只会用唯一一个工作线程来执行任务
缺点:它会创建一个Integer.MAX_VALUE长度的阻塞队列。
ExecutorService service2 = Executors.newCachedThreadPool();
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程。
缺点:它的最大线程数量为Integer.MAX_VALUE
ExecutorService service1 = Executors.newScheduledThreadPool()
创建一个定长线程池,支持定时及周期性任务执行。
缺点:它的最大线程数量为Integer.MAX_VALUE

public class TestThread4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
         //使用线程池可以控制资源,重复利用资源,稳定服务器性能。
        //创建一个固定线程数量的线程池,线程数量为10。
        ExecutorService service = Executors.newFixedThreadPool(10);
        //提交线程的两种方式:
        //1.submit(),返回 Future<T>,可以获取返回结果
        Future<Integer> submit = service.submit(new TestThread3());
        //2.execute(),无返回值。
        service.execute(new TestThread2());
    }
}

当前线程:pool-1-thread-1
运行结果:5

线程池七大参数:

  public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) 
/**
     * @param corePoolSize
     *       核心线程数【一直存在,除非设置allowCoreThreadTimeOut】,线程池    
     *       创建好以后就准备就绪的线程数量,等待执行任务
     * @param maximumPoolSize 
     *       线程池允许的最大的线程数量,可以控制资源
     * @param keepAliveTime 
     *       存活时间,如果当前线程数量大于核心数量时,空闲线程释放时间
     * @param    
     *       keepAliveTime 的时间单位。
     * @param workQueue 
     *       阻塞队列。如果任务有很多, 就会将目前多的任务放在队列里面。
     *       只要有线程空闲,就会去队列里面取出新的任务继续 执行。
     * @param threadFactory 
     *       线程的创建工厂,可以自定义线程名称。
     * @param handler 
     *       拒绝策略,如果阻塞队列满了,按照我们指定的拒绝策略拒绝执行任务。

拒绝策略:
RejectedExecutionHandler提供了四种方式来处理任务拒绝策略:
DiscardOldestPolicy:丢弃队列中最老的任务
AbortPolicy:抛异常(默认)
CallerRunsPolicy:将任务分给调用线程来执行
DiscardPolicy:直接丢弃

工作顺序 :
1、线程池创建,准备好core数量的核心线程,准备接受任务
2、任务进来,用core中空闲的线程执行。
       1)、core线程没有空闲的,就将再进来的任务放入阻塞队列中。当core线程空闲就去阻塞队列获取任务执行。
        2)、阻塞队列满了,就直接开新的线程执行,最大只能开到max指定的数量。
        3)、所有任务执行完毕,大于core线程数量的空闲线程,会在keepAliveTime指定的时间后,自动销毁,最终保持到core大小的线程数量。
4)、如果线程数已经达到max的数量 ,还有新任务进来,就会使用指定的拒绝策略进行处理。
3、所有的线程创建都是由指定的factory创建。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容