Reputation: 18171
I have two timers tm1
and tm2
and one timer event handler ts
. Can I be sure that function onTimeout()
will ever be called only by one timer (second timer will wait for onTimout()
exit)? If no - how to achieve that? I must use Java 1.4 for this task.
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");
}
}
Upvotes: 0
Views: 902
Reputation: 834
Each Timer runs tasks in it's own thread. So you can be sure two timers are able to call this method concurrently, and they won't wait for an other timer task completion.
You should make the target method synchronized
in order to prevent concurrent execution. There are a number of other approaches how you can achieve the goal.
I suggest reading this Oracle tutorial about concurrency.
Upvotes: 2