定时器Timer、线程(池)

定时器的使用:
题目:每隔两秒创建一个线程(线程总共创建5个线程),每个线程每隔两秒打印一句话(每个线程打印3句话)
涉及要点:线程(Thread)、线程池(ExecutorService)、synchronized(同步)
定时器(Timer):定时器timer调用schedule方法执行任务,第一个参数TimerTask是任务,第二个参数表示任务在多少秒后执行,第三个参数表示任务每隔多少秒执行一次(执行周期)。

用于标记次数的类Single1

package cn.lf.day090502;
public class Single1 {
    public int index = 0;
}

用于实现每个线程打印三句话的类MyThread3

package cn.lf.day090502;

import java.util.Timer;
import java.util.TimerTask;

public class MyThread3  extends Thread{
    public void run(){
        timerTest();
    }

    //同步
    public synchronized void timerTest(){
        Timer timer = new Timer();
        Single1 s = new Single1();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                s.index++;  //计数
                System.out.println("线程:"+Thread.currentThread());
                if (s.index == 3) {
                    //public void cancel():终止计时器
                    timer.cancel();  
                }
            }
        }, 0, 1000);
    }
}

测试类MyThread3Test

package cn.lf.day090502;
/**
 * 定时器的使用:
        题目:每隔两秒创建一个线程(线程总共创建5个线程),每个线程每隔两秒打印一句话(每个线程打印3句话)
 * 
 */
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThread3Test {
    public static void main(String[] args) {
         Timer timer = new Timer(); 
         //public interface ExecutorService extends Executor
         //ExecutorService继承于Executor的方法;void execute(Runnable command) 
         //public class Executors extends Object 
         //public static ExecutorService newFixedThreadPool(int nThreads)
         //创建一个可重用固定线程数的线程池
         ExecutorService executorService = Executors.newFixedThreadPool(2);
         Single1 s = new Single1();
            //public void schedule(TimerTask task,long delay,long period)
            timer.schedule(new TimerTask() {  
                public void run() {  
                     s.index++;
                     System.out.println("创建了线程"+(s.index));
                     //void execute(Runnable command)
                     //command:被执行的任务
                     executorService.execute(new MyThread3());
                     if (s.index == 5) {
                         //--方法--void shutdown()
                         //启动一次顺序关闭,执行以前提交的任务,但不接受新任务。
                        executorService.shutdown(); 
                        timer.cancel();  //关闭定时器
                    }
                }  
            }, 0, 2000);  
    }
}

程序运行结果:
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值