我用Timertask写了一个定时任务,它可以每2秒钟执行一次,这时候,我希望第一次任务执行的时候,第二次不要执行,也就是说,希望这些任务顺序进行的.
但在实现过程中发现,定时任务每2秒一次,它打断了第一次任务的执行,结果是交叉在一起了.高手出个主意,谢谢

解决方案 »

  1.   

    还要问一点,我用的这个Timertask执行任务的时候,生成了多个线程去执行这个任务,如何判断这些线程都已经完成呢?
      

  2.   

    java的多线程我没做过啊
    不过我以前做过vc++的多线程
    我用了一个最笨的办法
    那就设置一个数组
    数组长度就是线程数
    初始值为0
    有一个线程开始,对应的下标的数组值为1,如出错则置-1,正常完成置2
    全部完成怎清零不过这个方法笨了点
      

  3.   

    谢谢了,使用想起了CAS,问题搞定了,和你和方法类似
      

  4.   


    class ThreadDemo{
    public static void main(String args[])throws Exception{
    for (int i=0; i<10; ++i) {
    new Thread(new MyThread(i)).start();
    }
    }
    }class MyThread implements Runnable{
    public final static String lock = new String();
    private int id;
    public MyThread(int id){
    this.id = id;
    };
    public void run(){
    synchronized(lock){
    try{
    System.out.println(this);
    Thread.sleep(2000);
    }catch(InterruptedException ie){
    System.out.println(this+": exception!");
    }
    }
    }

    public String toString(){
    return ""+id;
    }
    }