5
I am implementing a Scheduler to run some threads on my system at x time intervals. The big problem is that if thread 1 has not yet finished running, 2 does not start, even though its time has come.
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");
}
}
Executioner
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 don’t use Tomcatee.
Desired Result:
When starting the program, the first thread will be created. 10 seconds later, although the first thread is still in the loop, the second thread is also created and starts to rotate.
@Carlosheuberger actually, I want a new instance of the "Minhathread" class. That is, there will be 2 "Minhathread" running at the same time. Maybe I’m wrong there?
– user94991
@Carlosheuberger got it!! Could you give me a brief example of this solution as an answer? At the same time I’ll look here and see if I can solve it too.
– user94991
@Carlosheuberger I’ll try, thank you!
– user94991
@Carlosheuberger I implemented your solution worked, my only concern is: Can creating a thread to call another thread cause me any problems? Or the "other thread" having the sole function of calling "my thread" will make the call and "die", so there is no problem?
– user94991