[7] Thread and thread pool

1. The life cycle of a thread:

 

*start() starts a new thread and can only be called once. The run() method does not start a new thread, but simply calls the method.

* currentThread() to get the current thread

* getName() to get the name of the thread

* setName() sets the name of the thread

* Yield()The thread that calls this method releases the current CPU execution rights. Note: But the current thread may still preempt CPU resources

* join() calls the join() method of thread B in thread A, which means: when this method is executed, thread A stops running until the execution of thread B is completed, thread A then executes the code after join()

* isAlive() determines whether the thread is still alive

* sleep(long l) makes the thread that calls the method sleep for l milliseconds. At this time, other threads can use cpu resources, and the thread that calls this method cannot use cpu resources, but the thread still holds a lock

* setPriority(int newPriority) sets the priority of the thread, the minimum is 1, the maximum is 10, and the default is 5. The higher the priority, the greater the possibility of obtaining cpu resources, and the higher priority is not necessarily executed first Thread

note:

The sleep() method will not release the lock, the wait() method will release the lock

Two, thread pool

/*

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

*

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

*  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();

    }



}

Seven parameters of the Java thread pool:

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);

...

}

The first three construction methods actually call the fourth construction method to initialize the thread pool

corePoolSize: the number of core threads, that is, the number of threads in the thread pool just created

maximumPoolSize: the maximum number of threads in the thread pool

keepAliveTime: Idle thread retention time to prevent the thread from being unused for a long time (lazy). If the thread is not used for more than this time, the thread will be destroyed

unit: reserved unit of idle thread time

workQueue (BlockingQueue<Runnable> type): Blocking queue, storing tasks waiting to be executed, the parameters are ArrayBlockingQueue, LinkedBlockingQueue, SynchronousQueue optional.

threadFactory (ThreadFactory type): Specify thread factory

handler (RejectedExecutionHandler type): Thread pool's processing strategy for rejected tasks.

The following is the processing strategy:

ThreadPoolExecutor.AbortPolicy: The default policy, discarding tasks and throwing RejectedExecutionException.

ThreadPoolExecutor.DiscardPolicy: also discards tasks, but does not throw exceptions.

ThreadPoolExecutor.DiscardOldestPolicy: Discard the first task in the queue and try to add the task again. If it fails, repeat the process.

ThreadPoolExecutor.CallerRunsPolicy: the task is handled by the calling thread

Guess you like

Origin blog.csdn.net/Jack_PJ/article/details/88015022