时间段内线程运行,时间段外线程停止

解决方案 »

  1.   

    没用过Timer,Timer好像只能定时执行,不能到时间停止吧?具体怎么搞,再弄个Timer去停?
      

  2.   

    在timer里面写new Thread{}的代码,做好控制就可以了。
      

  3.   

    Timer类是用来执行任务的类,接收一个TimerTask做参数Timer有两种执行任务的模式,最常用的是schedule,它可以以两种方式执行任务:1:在某个时间(Data),2:在某个固定的时间之后(int delay).这两种方式都可以指定任务执行的频率.例子:import java.io.IOException;
    import java.util.Timer;public class TimerTest
    {
        public static void main(String[] args)
        {
            Timer timer = new Timer();
            //在1秒后执行此任务,每次间隔2秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
            timer.schedule(new MyTask(), 1000, 2000);
            //测试停止此while循环
            while(true)
            {
                try
                {
                    int ch = System.in.read();
                    if(ch-'c'==0)
                    {
                        //退出任务
                        timer.cancel();
                    }
                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }    static class MyTask extends java.util.TimerTask
        {
            public void run()
            {
                //TODO Auto-generated method stub
                System.out.println("________");
            }
        }
    }