public class ThreadStarvation implements Runnable{
long startTime=System.currentTimeMillis();
Timer t;
class RunnerTask extends TimerTask {
public void run(){
if((System.currentTimeMillis()- startTime)< 100000){
System.out.println(Thread.currentThread().getName()+": in timer task run() method"+" : "+Calendar.getInstance().getTime());
}
else
t.cancel();
}
}
public synchronized void synchronizedTimerMethod(){
try{
Thread.sleep(1000);
t=new Timer();
t.schedule(new RunnerTask(), 0, 2000);
}
catch(InterruptedException ie){}
}
public void run(){
synchronizedTimerMethod();
}
public static void main(String[] args) {
ThreadStarvation ts1=new ThreadStarvation();
Thread t1=new Thread(ts1);
Thread t2=new Thread(ts1);
t1.start();
t2.start();
}
}
Three doubts is there in above program :
1) What I want from this program was that when thread t1 starts, goes to synchronized method synchronizedTimerMethod() will lock object ts1 and should locked it until timer object breached the condition. Hence Thread t2 will unable to gain regular access to shared resources ts1 and is unable to make progress and will go into starvation. But this is not happening. Is it not possible with Timer class ? I am novice to it.
2) When thread t1 starts, it goes to synchronized method synchronizedTimerMethod and the object ts1 will be locked. The object ts1 will not be released until timer object is scheduled till condition is breached. But what is happening thread t1 timer object first scheduled start at that time only Thread t2 enters synchronized method synchronizedTimerMethod. Is object ts1 got released due to Timer run method?
3) Also When both thread breached the condition the task is not cancelled, in particular the program stucks or I think it goes into deadlock. WHY?
I rewritten my code as below :
public class ThreadStarvation implements Runnable{
long startTime=System.currentTimeMillis();
final Timer t=new Timer;
class RunnerTask extends TimerTask {
public void run(){
if((System.currentTimeMillis()- startTime)< 100000){
System.out.println(Thread.currentThread().getName()+": in timer task run() method"+" : "+Calendar.getInstance().getTime());
}
else
t.cancel();
}
}
public synchronized void synchronizedTimerMethod(){
try{
Thread.sleep(1000);
t.schedule(new RunnerTask(), 0, 2000);
}
catch(InterruptedException ie){}
}
public void run(){
synchronizedTimerMethod();
}
public static void main(String[] args) {
ThreadStarvation ts1=new ThreadStarvation();
Thread t1=new Thread(ts1);
Thread t2=new Thread(ts1);
t1.start();
t2.start();
}
}
Now I just want that the task should get stopped. For that I made the Timer object as final. Then also the task don't seem to cancel. Is some more modification is needed ? Please help.