定时器Timer、线程(池)

来源:互联网 发布:boot repair ubuntu 编辑:程序博客网 时间:2024/05/20 17:08

定时器的使用:
题目:每隔两秒创建一个线程(线程总共创建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);      }}

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

原创粉丝点击