【七】线程及线程池

一、线程的生命周期:

 

*start()开启一个新的线程,只能调用一次,run()方法不会开启一个新的线程,只是简单的调用方法。

* currentThread()获取当前的线程

* getName()获取线程的名称

* setName()设置线程的名称

* yield()调用此方法的线程释放当前的CPU执行权,注意:但是当前线程可能还会抢占到CPU资源

* join()在A线程中调用B线程的join()方法,表示:当执行到此方法A线程停止运行,直至B线程执行完成,A线程接着join()后的代码执行

* isAlive()判断线程是否还存活

* sleep(long l)使调用方法的线程睡眠l毫秒,此时其他线程可以使用cpu资源,而调用该方法的线程不能使用cpu资源,但是该线程还持有锁

* setPriority(int newPriority)设置线程的优先级,最小为1,最大为10,默认为5,优先级越高,代表获得cpu资源的可能性就越大,并不是一定会先执行优先级高的线程

注意:

sleep()方法不会释放掉锁,wait()方法会将锁释放掉

二、线程池

/*

* 一、线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。

*

* 二、线程池的体系结构:

*  java.util.concurrent.Executor : 负责线程的使用与调度的根接口

*      |--**ExecutorService 子接口: 线程池的主要接口

*          |--ThreadPoolExecutor 线程池的实现类(继承AbstractExecutorService,AbstractExecutorService实现ExecutorService接口)

*          |--ScheduledExecutorService 子接口:负责线程的调度

*              |--ScheduledThreadPoolExecutor  :继承 ThreadPoolExecutor, 实现  ScheduledExecutorService

*

* 三、工具类 : Executors

* ExecutorService newFixedThreadPool() : 创建固定大小的线程池

* ExecutorService newCachedThreadPool() : 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。

* ExecutorService newSingleThreadExecutor() :  创建单个线程池。线程池中只有一个线程

*

* ScheduledExecutorService  newScheduledThreadPool() : 创建固定大小的线程,可以延迟或定时的执行任务。

*/

public class TestThreadPool {

    public static void main(String[] args)  throws InterruptedException, ExecutionException  {

        //创建线程池

        ExecutorService pool =  Executors.newFixedThreadPool(5);

        List<Future<Integer>> futures = new  ArrayList<>();

        for(int i=1;i<=10;i++){

            Future<Integer> future =  pool.submit(new Callable<Integer>() {

                int sum=0;

                @Override

                public Integer call() throws  Exception {

                    for(int i=0;i<=100;i++){

                        sum+=i;

                    }

                    return sum;

                }

                

            });

            futures.add(future);

        }

        for(Future future:futures){

            System.out.println(future.get());

        }

        /*//Runnable的形式

        ThreadPoolDemo demo = new  ThreadPoolDemo();

        //添加任务

        for(int i=1;i<=10;i++){

            pool.submit(demo);

        }*/

        //关闭线程池

        pool.shutdown();

    }

}

class ThreadPoolDemo implements Runnable{

    @Override

    public void run() {

        for(int i=0;i<=10;i++){

            System.out.println(Thread.currentThread().getName()+":"+i);

        }

    }

    

}

ScheduledThreadPool:

package com.pj.test.juc2;



import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.ScheduledFuture;

import java.util.concurrent.TimeUnit;



public class TestScheduledThreadPool {



    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);

        for(int i=0;i<5;i++){

            ScheduledFuture<Integer> schedule = pool.schedule(new Callable<Integer>() {

                int rand = (int) (Math.random()*100);

                @Override

                public Integer call() throws Exception {

                    System.out.println(rand);

                    return rand;

                }

                

            },3000,TimeUnit.MILLISECONDS);

            System.out.println(schedule.get());

        }

        pool.shutdown();

    }



}

Java线程池的七个参数:

public class ThreadPoolExecutor extends AbstractExecutorService {

.....

public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,

BlockingQueue<Runnable> workQueue);

public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,

BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory);

public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,

BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler);

public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,

BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler);

...

}

前三个构造方法实际上就是调用第四个构造方法来进行线程池的初始化的

corePoolSize:核心的线程数量,即刚刚创建的线程池中线程的个数

maximumPoolSize:线程池中最大的线程数量

keepAliveTime:空闲的线程保留时间,防止线程长时间未使用(偷懒),超出该时间未使用,那么将会将该线程销毁

unit:空闲的线程时间的保留单位

workQueue(BlockingQueue<Runnable>类型):阻塞队列,储存等待执行的任务,参数有ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue可选。

threadFactory(ThreadFactory类型):指定线程工厂

handler(RejectedExecutionHandler类型):线程池对拒绝任务的处理策略。

以下为处理策略:

ThreadPoolExecutor.AbortPolicy:默认策略,丢弃任务并抛出RejectedExecutionException异常。

ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。

ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,再尝试添加任务,如果失败,重复此过程。

ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值