I tried another way of doing this and the following is the code:
import java.util.Date;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.StringTokenizer;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.text.ParsePosition;
import java.util.ArrayList;
public class TimerTest {
String arr[]={"element1", "element2"};
public static RunTask task = null;
public static int RETRY_COUNT = 4;
ArrayList arraylist = new ArrayList();
Date today, future;
public static void main(String[] args) {
new TimerTest();
}
public TimerTest() {
//Different ways to Add Elements to the arraylist
for(int i=0;i<arr.length;i++) {
arraylist.add(i,arr[i]);
}
String strCode = null;
try {
for(int i = 0;i< arraylist.size();i++) {
strCode = (String)arraylist.get(i);
task = new RunTask(strCode, RETRY_COUNT);
task.start();
System.out.println( "\n["+ Thread.currentThread().getName()+"] Started the
thread ->" + task.getName());
System.out.println("Sleeping for 2 seconds...");
Thread.sleep(2000L);
}
}
catch(Exception e) {
}
}
}
class RunTask extends Thread {
String strCode = null;
RunTask task;
int iRetryCount = 0;
public RunTask(String code, int iCount) {
strCode = code;
iRetryCount = iCount;
}
public RunTask(String code, int iCount, RunTask rt) {
strCode = code;
task = rt;
iRetryCount = iCount;
}
public void run() {
try {
iRetryCount--;
if(task != null) {
System.out.println("Sleeping for 30 seconds...");
Thread.sleep(30000);
if(! task.isAlive()) {
System.out.println(Thread.currentThread().getName() + " is dead...");
}
}
// do someting
if(iRetryCount != 0) {
task = new RunTask(strCode, iRetryCount, this);
task.start();
System.out.println( "\n["+ Thread.currentThread().getName()+"] Stopped & terminated." +
"Starting thread ->" + task.getName());
}
Thread.sleep(1000L);
System.out.println(Thread.currentThread().getName() + " sleeping for 1 second...");
}
catch (ThreadDeath e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
But, I have a question. I am killing the current Thread and creating another Thread and ask it to sleep for 30 seconds. This is just a simulation. My actual program will wait for 45 minutes.
My questionis, is there any other better way of doing it?
Thanks,
Tom