I'm implementing a scheduler to run some threads on my system at x time intervals. The big problem is that if thread 1 still has not finished running, a 2 does not start, even its time having arrived.
In the example below I "forced" this error because I was suspicious that this could be happening.
Thread
package backgroundProcesses;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;
public class MinhaThread implements Runnable {
@Override
public void run() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("FOI, COMEÇOOU A THREAD: " + sdf.format(cal.getTime()));
int i = 0;
while(i < 1000000000) {
int a = 1;
}
System.out.println("CHEGOU AO FIM");
}
}
Executor
package backgroundProcesses;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ExecutorThreads implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
scheduler = Executors.newScheduledThreadPool(4);
scheduler.scheduleAtFixedRate(new MinhaThread(), 0, 10, TimeUnit.SECONDS);
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
scheduler.shutdownNow();
}
}
I'm running the application on a simple Tomcat, I do not use TomcatEE.
Desired Outcome:
When you start the program, the first thread will be created. 10 seconds later, even though the first thread is still in the loop, the second thread is also created and starts rolling.