zoukankan      html  css  js  c++  java
  • Java 线程池的原理与实现学习(二)

    java类库中提供的线程池简介:

    java提供的线程池更加强大,相信理解线程池的工作原理,看类库中的线程池就不会感到陌生了。

    • execute(Runnable command):履行Ruannable类型的任务
    • submit(task):可用来提交Callable或Runnable任务,并返回代表此任务的Future对象
    • invokeAll(collection of tasks):执行给定的任务,当所有任务完成时,返回保持任务状态和结果的 Future 列表.
    • shutdown():在完成已提交的任务后封闭办事,不再接管新任务
    • shutdownNow():停止所有正在履行的任务并封闭办事。
    • isTerminated():测试是否所有任务都履行完毕了。
    • isShutdown():测试是否该ExecutorService已被封闭

    1、固定大小线程池

    	import java.util.concurrent.Executors; 
    	import java.util.concurrent.ExecutorService;
    	ExecutorService pool = Executors.newFixedThreadPool(2);
    	pool.execute(t1);
    	pool.shutdown();
    

    2、单任务线程池

    	ExecutorService pool = Executors.newSingleThreadExecutor();
    

    3、可变尺寸线程池

    	ExecutorService pool = Executors.newCachedThreadPool();
    

    4、延迟连接池

    	ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
    	pool.schedule(t4, 10, TimeUnit.MILLISECONDS);
    

    5、单任务延迟连接池

    	ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
    

    1.schedule         

      schedule(Runnable command, long delay, TimeUnit unit),schedule方法被用来延迟指定时间后执行某个指定任务。  

    a.Java代码如下:

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    //内部线程工作类
    class Job implements Runnable {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    	public void run() {
    		try {
    			Thread.sleep(5000);
    		} catch (InterruptedException ex) {
    			ex.printStackTrace();
    		}
    		System.out.println("do something  at:" + sdf.format(new Date()));
    	}
    }
    public class ScheduledExecutorServiceTest {
    	public static void main(String[] args) {
    		ScheduledExecutorService schedule = Executors.newScheduledThreadPool(5);
    		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    		System.out.println("begin to do something at:"+ sdf.format(new Date()));
    		schedule.schedule( new Job(), 1, TimeUnit.SECONDS);
    	}
    }
    

    b.输出如下: 

      begin to do something at:2015-04-27 10:29:56
      do something  at:2015-04-27 10:30:02

    注:此时程序不会退出,若想让程序退出,需要加上schedule.shutdown();

    ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRateScheduleWithFixedDelay

    ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;

    ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。

    由此可见,ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。

    2.scheduleWithFixedDelay             

       scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,TimeUnit unit)         

           创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟,如果任务的执行时间超过了廷迟时间(delay),下一个任务则会在当前任务执行所需时间+delay)后执行。    

    a.Java代码如下:

    public class ScheduledExecutorServiceTest {
    	public static void main(String[] args) {
    		ScheduledExecutorService schedule = Executors.newScheduledThreadPool(5);
    		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    		System.out.println(" begin to do something at:"+ sdf.format(new Date()));
    		schedule.scheduleWithFixedDelay(new Job(), 1, 2, TimeUnit.SECONDS);
    	}
    }
    

        b.输出如下:

    1. begin to do something at:2012-08-03 09:36:53
    2. do something at:2012-08-03 09:36:59
    3. do something at:2012-08-03 09:37:06
    4. do something at:2012-08-03 09:37:13

    3.scheduleAtFixedRate             

       scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnitunit)            

          创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。如果任务的执行时间小于period,将会按上述规律执行。否则,则会按任务的实际执行时间进行周期执行。    

    a.代码如下:

    public class ScheduledExecutorServiceTest { 
    public static void main(String[] args) { 
            ScheduledExecutorService schedule = Executors.newScheduledThreadPool(2); 
            final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
            System.out.println(" begin to do something at:" + sdf.format(new Date())); 
            schedule.scheduleAtFixedRate(new Job(), 1,2, TimeUnit.SECONDS); 
        } 
    }
    

        b.结果输出:

    1. begin to do something at:2012-08-04 08:53:30
    2. do something at:2012-08-04 08:53:36
    3. do something at:2012-08-04 08:53:41
    4. do something at:2012-08-04 08:53:46
    5. do something at:2012-08-04 08:53:51
  • 相关阅读:
    Visual Studio 进行单元测试时如何附加被测试文件的方法总结
    PowerDesigner实体模型CDM中关于建立Entity之间关系的备忘
    【转帖】C# 与 C++ 数据类型对照
    【转帖】解决继承窗体或用户控件时“visual继承当前被禁用,因为基类引用设备特定的组件或包含 p/invoke”问题
    【Winform窗体控件开发】之五 实现类型转换器TypeConverterAttribute
    SQL 使用CONVERT函数 格式化日期
    【转帖】const 与 readonly 的区别
    【转帖】C#与C Windows API数据类型对应关系
    【.Net Compact Framework开发】 使用 Visual Studio 对移动项目进行Unit Testing的方法总结
    【部署】Visual Studio 2008 打包部署.Net Framework 2.0 应用程序提示需要安装.Net Framework 3.5的解决方法
  • 原文地址:https://www.cnblogs.com/whsa/p/4277001.html
Copyright © 2011-2022 走看看