java 定时任务执行

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/u012604299/article/details/81001506
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * java 定时执行的实现
 * @author gzn
 */
public class InteveralTest {
	
	/**
	 * 测试线程
	 */
	public void ThreadTest(){
		final long timeInteveral = 1*1000;
		
		Runnable runable = new Runnable() {
			// 定义计数
			int count = 0;
			@Override
			public void run() {
				try{
					do{
						System.out.println("run " + count);
						count ++;
						if(10 == count){
							System.out.println("线程结束!");
							break;
						}
						// 线程沉睡1秒
						Thread.sleep(timeInteveral);
					}while(60 >= count);
				}catch(InterruptedException e){
					System.out.println(e);
				}
			}
		};
		// 线程初始化
		Thread thread = new Thread(runable);
		// 开始执行
		thread.start();
	}
	
	/**
	 * 测试定时任务
	 */
	public void TimerTest(){
		TimerTask task = new TimerTask() {
			int count = 0;
			@Override
			public void run() {
				System.out.println("TimerTask times : " + count);
				count++;
				if(10 == count){
					// 调用cancel方法线程终止,但资源未释放
					this.cancel();
					// 调用系统gc方法进行资源回收,工程中不建议使用
					System.gc();
				}
			}
		};
		
		Timer timer = new Timer();
		// 任务执行前等待时间
		long delay = 0;
		// 执行间隔时间
		long period = 1*1000;
		timer.scheduleAtFixedRate(task, delay, period);
	}
	
	/**
	 * Scheduled
	 * @throws InterruptedException 
	 */
	public void ScheduledTest() throws InterruptedException{
		Runnable runable = new Runnable() {
			// 定义计数
			int count = 0;
			@Override
			public void run() {
				System.out.println("run " + count);
				count ++;
			}
		};
		
		ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor();
		/**
		 * Runnable command, 任务名
		 * long initialDelay, 等待时间
		 * long period, 间隔时间
		 * TimeUnit unit 入参时间类型
		 */
		scheduled.scheduleAtFixedRate(runable, 0, 1*1000, TimeUnit.MILLISECONDS);
		
		// 线程沉睡10秒
		Thread.sleep(10000);
		// 任务停止
		scheduled.shutdown();
	}
	
	/**
	 * 主线程每秒执行一次
	 * @throws InterruptedException
	 */
	public void MainThreadSleep() throws InterruptedException{
		// 标记(不常用)
		finish:
		for(int i = 0;i < 60;i++){
			if(i != 60){
				System.out.println("count : " + i);
				// 沉睡1秒
				Thread.sleep(1000);
				if(10 == i){
					break finish;
				}
			}
		}
	
		System.out.println("线程结束!");
	}
	
	public static void main(String[] args) throws InterruptedException {
		InteveralTest test = new InteveralTest();
		// 线程测试
//		test.ThreadTest();
		// timer定时任务测试
//		test.TimerTest();
		// 测试计划任务
//		test.ScheduledTest();
		
		test.MainThreadSleep();
	}
	
}

猜你喜欢

转载自blog.csdn.net/u012604299/article/details/81001506