黑马程序员技术交流社区

标题: timer类的交替调度 [打印本页]

作者: xgm    时间: 2016-3-18 00:31
标题: timer类的交替调度
  1. * 目的:进一步了解Timer类,完成Timer的交替调度
  2. *
  3. */
  4. public class TestTimer2 {

  5.         static Timer timer = new Timer();
  6.         public static void main(String[] args) {
  7.                
  8.                
  9.                 timer.schedule(new MyTimerTask(), 2000);
  10.                 /*timer.schedule(new TimerTask(){
  11.                        
  12.                         public void run() {
  13.                                 System.out.println("缘分这东西太难搞了");
  14.                                 new Timer().schedule(this, 4000);   //Task already scheduled or cancelled
  15.                         }}, 2000);*/
  16.                
  17.                 int i = 0;
  18.                 while(true){
  19.                         System.out.println(++i);
  20.                         try {
  21.                                 Thread.sleep(1000);
  22.                         } catch (InterruptedException e) {
  23.                                 e.printStackTrace();
  24.                         }
  25.                 }
  26.                
  27.         }
  28.         static int num = 0;
  29.         static class MyTimerTask extends TimerTask{
  30.                
  31.                
  32.                 public void run() {
  33.                         num = (num+1)%2;   //判断余数为1或者0
  34.                         System.out.println("头发花白的程序员");
  35.                         timer.schedule(new MyTimerTask(), 2000*(num+1));   //实现交替进行
  36.                 }
  37.                
  38.         }
  39. }
复制代码

作者: zx7660    时间: 2016-3-18 12:49
恩   不错




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2