java线程池和任务调度Timer类

线程池

创建和销毁对象是非常消耗时间的,创建对象需要分配内存等资源,销毁对象虽然不用程序员操心,但是垃圾回收器会在后台一直跟踪并销毁。对于正常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
为了提高性能,可以使用线程池,创建多个线程,然后放入线程池中,使用时直接获取引用,不适用时放回池中。可以避免频繁创建销毁,实现重复利用。
线程池的好处:

  1. 提高响应速度,减少了创建新线程的时间

  2. 降低资源消耗,重复利用线程池中的线程,不需要每次都创建

  3. 提高线程的可管理性,避免线程无限创建,从而消耗系统资源,降低系统稳定性,甚至内存溢出或者cpu耗尽。
    线程池的应用场合:

  4. 需要大量线程,并且完成任务的时间短

  5. 对性能要求苛刻

  6. 接受突发性的大量请求

使用线程池执行大量的Runnable命令

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {
	public static void main(String[] args) {
		//如何创建一个线程池
		//(1)创建一个线程池,线程池中只有一个线程对象
		//ExecutorService pool1=Executors.newSingleThreadExecutor();
		//(2)创建一个线程池,线程池中有线程的数量固定
		//ExecutorService pool1=Executors.newFixedThreadPool(10);
		//(3)创建一个线程池,线程池中的线程的数量可以动态的改变
		ExecutorService pool1=Executors.newCachedThreadPool();
		/**使用线程池执行大量的Runnable命令*/
		for(int i=0;i<20;i++){
			final int n=i;
			//使用匿名内部类//任务
			Runnable command=new Runnable() {
				
				@Override
				public void run() {
					System.out.println("开始执行:"+n);
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("执行结束:"+n);
				}
			};//任务结束
			//将任务交给线程池中的线程去执行
			pool1.execute(command);
		}
		//关闭线程池
		pool1.shutdown();
	}
}

使用线程池执行大量的Callable命令

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test2 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// 如何创建一个线程池
		// (1)创建一个线程池,线程池中只有一个线程对象
		 //ExecutorService pool1=Executors.newSingleThreadExecutor();
		// (2)创建一个线程池,线程池中有线程的数量固定
		 ExecutorService pool1=Executors.newFixedThreadPool(10);
		// (3)创建一个线程池,线程池中的线程的数量可以动态的改变
		//ExecutorService pool1 = Executors.newCachedThreadPool();
		//创建一个集合
		 List<Future> list=new ArrayList<Future>();
		/**使用线程池执行大量的Callable任务*/
		for(int i=0;i<20;i++){
			//使用匿名内部类
			//创建任务
			Callable<Integer> task=new Callable<Integer>() {

				@Override
				public Integer call() throws Exception {
					Thread.sleep(2000);
					return (int)(Math.random()*10)+1;
				}
				
			}; //任务结束
			//将任务交能线程池
			Future f=pool1.submit(task);
			list.add(f);
			//System.out.println(f.get());
		}
		System.out.println("ok?");
		//遍历集合
		 for(Future ff:list){
			 System.out.println(ff.get());
		 }
		 System.out.println("OK!");
		//关闭线程池
		pool1.shutdown();
	}
}
任务调度

什么是调度?
调度就是在不同时间点或者指定的时间点或者间隔多长时间去执行任务。
Timer类概念:
一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。
Timer的常用方法
在这里插入图片描述

import java.util.Date;
import java.util.TimerTask;
/**
 * 任务
 * @author Administrator
 *
 */
public class Clock extends TimerTask{
	long time=1000;//1秒
	@Override
	public void run() {
		Date date=new Date(time);
		System.out.println(date.toLocaleString());
		time+=1000;
	}

}
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {
	public static void main(String[] args) {
		//(1)创建Timer的对象
		Timer t=new Timer();
		//(2)调用schedule()方法去执行任务
		//创建任务类的对象
		TimerTask task=new Clock();
		           //要执行的任务,第二个参数是任务的执行开始时间 ,第三个参数是每隔多长时间执行一次
		t.schedule(task, new Date(System.currentTimeMillis()+1000), 1000);
		
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45684562/article/details/107926614