计时器事件是否同步?

时间:2016-02-19 12:14:42

标签: java multithreading timer

我有两个计时器tm1tm2以及一个计时器事件处理程序ts。我能确定函数onTimeout()只能由一个计时器调用(第二个计时器将等待onTimout()退出)吗?如果没有 - 如何实现?我必须使用Java 1.4来完成这项任务。

package thr;





import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

interface iTimerSupporter
{
    public void onTimeout();
}

class TimerSupporter implements iTimerSupporter 
{
    public void onTimeout()
    {
        System.out.println("time");     
    }   
}

public class TimeMachine  
{

    public static int TimerCount = 0;
    public  final int TimeoutValue = 5;
    public static int TimerID = 0;

    iTimerSupporter EventPrenumerator;

    private String info;
    static Timer timer = null;

    private String getDateTime(Date date)
    {
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        return dateFormat.format(date);
    }

    public class notif extends TimerTask
    {
        String info;
        Date started = new Date();
        Date stoped = null;


        public notif(String info)
        {
            this.info = info;
        }

        public void run()
        {
            if (EventPrenumerator != null)
                {
                    try
                    {
                    stoped = new Date();
                    System.out.println("main timeout "  + " started: " + getDateTime(started) + " stopped: "
                            + getDateTime(stoped) + " timeout ID=" + info );
                    EventPrenumerator.onTimeout();
                    }catch ( Exception e)
                    {
                        System.out.println("error in timeout event "+e.getMessage() );

                    }
                }
            timer.cancel();

        }
    }





    public void startTimer(String info)
    {
        TimerCount++;
        System.out.println("start . Will wait " + TimeoutValue + " timeout ID="+info  );
        timer = new Timer();
        notif n = new notif(info);
        this.info=info;
        timer.schedule(n, TimeoutValue * 1000);
    }




    public void startTimer()
    {

        info= Integer.toString (TimerID++);
        startTimer(info);
    }   



    public String state()
    {
        return "TimerCount=" + TimerCount+ " timeout ID="+info;
    }





    private void stopTimer()
    {
            TimerCount--;
            timer.cancel();
    }

    public static void main(String[] value)
    {
        TimerSupporter ts = new TimerSupporter();
        TimeMachine tm1 = new TimeMachine();
        tm1.EventPrenumerator = ts;
        TimeMachine tm2 = new TimeMachine();
        tm2.EventPrenumerator = ts;

        tm1.startTimer();
        tm2.startTimer();

        System.out.println("exit");

    }



}

1 个答案:

答案 0 :(得分:0)

每个Timer在其自己的线程中运行任务。因此,您可以确定两个计时器能够同时调用此方法,并且它们不会等待其他计时器任务完成。

您应该创建目标方法synchronized以防止并发执行。如何实现目标还有很多其他方法。 我建议阅读有关并发性的this Oracle tutorial