ScheduledThreadPool测试程序

1、ScheduledThreadPool类代码

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public final class ScheduledThreadPool
{
	private int threadNum = 10;
	
	private ScheduledExecutorService scheduledExec = null;

	public ScheduledThreadPool(String name)
	{
		scheduledExec = Executors.newScheduledThreadPool(threadNum, sThreadFactory);
	}
	
	public void scheduleWithFixedDelay(TimerTask task, long initialDelay, long delay)
	{
		if (initialDelay < 0)
		{
			throw new IllegalArgumentException("Nagtive initialDelay");
		}
		
		if (delay < 0)
		{
			throw new IllegalArgumentException("Negtive delay");
		}
		
		scheduledExec.scheduleWithFixedDelay(task, initialDelay, delay, TimeUnit.SECONDS);
	}
	
	public void schedule(TimerTask task, long delay)
	{
		if (delay < 0)
		{
			throw new IllegalArgumentException("Negtive delay");
		}
		scheduledExec.schedule(task, delay, TimeUnit.SECONDS);
	}
	
	public void shutdown()
	{
		if (null != scheduledExec)
		{
			scheduledExec.shutdown();
		}
		
		scheduledExec = null;
	}
	
	private static final ThreadFactory sThreadFactory = new ThreadFactory()
	{
		private final AtomicInteger mCount = new AtomicInteger(1);
		
		@Override
		public Thread newThread(Runnable r)
		{
			Thread thread = new Thread(r, "ScheduledThreadPool #" + mCount.getAndIncrement());
			
			// 设置线程为守护线程
			thread.setDaemon(true);
			return thread;
		}
		
	};
}

2、Test类代码

import java.io.IOException;
import java.util.TimerTask;

public class Test
{

	public static void main(String[] args)
	{
		// 线程任务1
		TimerTask task1 = new TimerTask()
		{
			
			@Override
			public void run()
			{
				try
				{
					Thread.currentThread().sleep(2000);
				}
				catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("task run1");
			}
		};
		
		// 线程任务2
		TimerTask task2 = new TimerTask()
		{
			
			@Override
			public void run()
			{
				try
				{
					Thread.currentThread().sleep(1000);
				}
				catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("task run2");
			}
		};
		
		ScheduledThreadPool threadPool  = new ScheduledThreadPool("pool");
		
		// 从线程池中取出线程,周期性执行任务1
		threadPool.scheduleWithFixedDelay(task1, 0, 3);
		
		// 从线程池中取出线程,周期性执行任务2
		threadPool.scheduleWithFixedDelay(task2, 0, 3);
		
		// 因线程池中的线程被设置为“守护线程”,主线程不能停止,否则主线程结束,线程池中的线程马上终止
		try
		{
			System.in.read();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
3、用JDK中的jvisualvm工具,观察线程的执行情况


3、考虑到应用程序中,可能仅存在一个线程池实例,将上面的ScheduledThreadPool改写为单例

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public final class ScheduledThreadPool
{
	private int threadNum = 10;
	
	private ScheduledExecutorService scheduledExec = null;
	
	private static ScheduledThreadPool instance = null;

	// 私有构造函数
	private ScheduledThreadPool(String name)
	{
		scheduledExec = Executors.newScheduledThreadPool(threadNum, sThreadFactory);
	}
	
	// 返回线程池单例
	public static ScheduledThreadPool getInstace(String name)
	{
		// 确保多线程安全
		synchronized (ScheduledThreadPool.class)
		{
			if (null == instance)
			{
				instance = new ScheduledThreadPool(name);
			}
		}
		
		return instance;
	}
	
	// 销毁线程池单例
	public static void destroy()
	{
		synchronized (ScheduledThreadPool.class)
		{
			if (null != instance)
			{
				instance = null;
			}
		}
	}
	
	public void scheduleWithFixedDelay(TimerTask task, long initialDelay, long delay)
	{
		if (initialDelay < 0)
		{
			throw new IllegalArgumentException("Nagtive initialDelay");
		}
		
		if (delay < 0)
		{
			throw new IllegalArgumentException("Negtive delay");
		}
		
		scheduledExec.scheduleWithFixedDelay(task, initialDelay, delay, TimeUnit.SECONDS);
	}
	
	public void schedule(TimerTask task, long delay)
	{
		if (delay < 0)
		{
			throw new IllegalArgumentException("Negtive delay");
		}
		scheduledExec.schedule(task, delay, TimeUnit.SECONDS);
	}
	
	public void shutdown()
	{
		if (null != scheduledExec)
		{
			scheduledExec.shutdown();
		}
		
		scheduledExec = null;
	}
	
	private static final ThreadFactory sThreadFactory = new ThreadFactory()
	{
		private final AtomicInteger mCount = new AtomicInteger(1);
		
		@Override
		public Thread newThread(Runnable r)
		{
			Thread thread = new Thread(r, "ScheduledThreadPool #" + mCount.getAndIncrement());
			
			// 设置线程为守护线程
			thread.setDaemon(true);
			return thread;
		}
		
	};
}

4、通过拜读左潇龙博客文章,发现上节中的线程池在并发场景下效率较低,修改为通过静态内部类的方式,创建单例对象

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public final class ScheduledThreadPool
{
	private ScheduledExecutorService scheduledExec = null;
	
	// 私有构造函数
	private ScheduledThreadPool(String name, int threadNum)
	{
		scheduledExec = Executors.newScheduledThreadPool(threadNum, sThreadFactory);
	}
	
	// 返回线程池单例
	public static ScheduledThreadPool getInstace()
	{
		return ScheduledThreadPoolInstance.instance;
	}
	
	public void scheduleWithFixedDelay(TimerTask task, long initialDelay, long delay)
	{
		if (initialDelay < 0)
		{
			throw new IllegalArgumentException("Nagtive initialDelay");
		}
		
		if (delay < 0)
		{
			throw new IllegalArgumentException("Negtive delay");
		}
		
		scheduledExec.scheduleWithFixedDelay(task, initialDelay, delay, TimeUnit.SECONDS);
	}
	
	public void schedule(TimerTask task, long delay)
	{
		if (delay < 0)
		{
			throw new IllegalArgumentException("Negtive delay");
		}
		scheduledExec.schedule(task, delay, TimeUnit.SECONDS);
	}
	
	public void shutdown()
	{
		if (null != scheduledExec)
		{
			scheduledExec.shutdown();
		}
		
		scheduledExec = null;
	}
	
	private static final ThreadFactory sThreadFactory = new ThreadFactory()
	{
		private final AtomicInteger mCount = new AtomicInteger(1);
		
		@Override
		public Thread newThread(Runnable r)
		{
			Thread thread = new Thread(r, "ScheduledThreadPool #" + mCount.getAndIncrement());
			
			// 设置线程为守护线程
			thread.setDaemon(true);
			return thread;
		}
		
	};
	
	// 通过静态内部类的方式,创建单例对象
	private static class ScheduledThreadPoolInstance
	{
		private static final String THREAD_POOL_NAME = "pool";
		private static final int THREAD_NUM = 10;
		static ScheduledThreadPool instance = new ScheduledThreadPool(THREAD_POOL_NAME, THREAD_NUM);
	}
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值