多线程与并发-----线程池的并发库的应用

    线程池:先创建多个线程放在线程池中,当有任务需要执行时,从线程池中找一个空闲线程执行任务,任务完成后,并不销毁线程,而是返回线程池,等待新的任务安排。

    线程池编程中,任务是提交给整个线程池的,并不是提交给某个具体的线程,而是由线程池从中挑选一个空闲线程来运行任务。一个线程同时只能执行一个任务,可以同时向一个线程池提交多个任务。


一、线程池创建方法:

    a、创建一个拥有固定线程数的线程池

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

    b、创建一个缓存线程池线程池中的线程数根据任务多少自动增删 动态变化

        ExecutorService threadPool = Executors.newCacheThreadPool();

    c、创建一个只有一个线程的线程池与单线程一样,但好处是保证池子里有一个线程,当线程意外死亡,会自动产生一个替补线程,始终有一个线程存活

        ExecutorService threadPool = Executors.newSingleThreadExector();


二、往线程池中添加任务

        threadPool.executor(Runnable)

三、关闭线程池:

        threadPool.shutdown()线程全部空闲,没有任务就关闭线程池

        threadPool.shutdownNow()  不管任务有没有做完,都关掉

        演示代码如下:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolTest {

	public static void main(String[] args) {
//		ExecutorService threadPool=Executors.newFixedThreadPool(5);//创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
//		ExecutorService threadPool=Executors.newCachedThreadPool();//创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。
		ExecutorService threadPool=Executors.newSingleThreadExecutor();//创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。
			
		for(int i=1;i<=10;i++){
			final int task=i;
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					for(int j=0;j<10;j++){
						try {
							Thread.sleep(30);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName()+" is loop of "+j+" for task "+task);
					}
				}
			});
		}
		System.out.println("all of tasks have committed!");
//		threadPool.shutdown();
//		threadPool.shutdownNow();
	}
}

运行结果为:

all of tasks have committed!
pool-1-thread-1 is loop of 0 for task 1
pool-1-thread-1 is loop of 1 for task 1
pool-1-thread-1 is loop of 2 for task 1
pool-1-thread-1 is loop of 3 for task 1
pool-1-thread-1 is loop of 4 for task 1
pool-1-thread-1 is loop of 5 for task 1
pool-1-thread-1 is loop of 6 for task 1
pool-1-thread-1 is loop of 7 for task 1
pool-1-thread-1 is loop of 8 for task 1
pool-1-thread-1 is loop of 9 for task 1
pool-1-thread-1 is loop of 0 for task 2
pool-1-thread-1 is loop of 1 for task 2
pool-1-thread-1 is loop of 2 for task 2
pool-1-thread-1 is loop of 3 for task 2
pool-1-thread-1 is loop of 4 for task 2
pool-1-thread-1 is loop of 5 for task 2
pool-1-thread-1 is loop of 6 for task 2
pool-1-thread-1 is loop of 7 for task 2
pool-1-thread-1 is loop of 8 for task 2
pool-1-thread-1 is loop of 9 for task 2
pool-1-thread-1 is loop of 0 for task 3
pool-1-thread-1 is loop of 1 for task 3
pool-1-thread-1 is loop of 2 for task 3
pool-1-thread-1 is loop of 3 for task 3
pool-1-thread-1 is loop of 4 for task 3
pool-1-thread-1 is loop of 5 for task 3
pool-1-thread-1 is loop of 6 for task 3
pool-1-thread-1 is loop of 7 for task 3

四、线程池启动定时器

    

    a、创建调度线程池,提交任务 延迟指定时间后执行任务

            Executors.newScheduledThreadPool(线程数).schedule(Runnable, 延迟时间,时间单位);

Executors.newScheduledThreadPool(3).schedule(new Runnable() {			
			@Override
			public void run() {
				System.out.println("bombing!");
			}
		}, 5, TimeUnit.SECONDS);

    b、创建调度线程池,提交任务,延迟指定时间执行任务后,间隔指定时间循环执行

            Executors.newScheduledThreadPool(线程数). scheduleAtFixedRate (Runnable, 延迟时间,间隔时间,时间单位);

Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {			
			@Override
			public void run() {
				System.out.println("bombing!");
			}
		}, 5, 3, TimeUnit.SECONDS);


注:

    所有的 schedule 方法都接受相对 延迟和周期作为参数,而不是绝对的时间或日期。将以 Date 所表示的绝对时间转换成要求的形式很容易。例如,要安排在某个以后的 Date 运行,可以使用:schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)


猜你喜欢

转载自blog.csdn.net/pengzhisen123/article/details/80289517