[英]TimerTask + multiThreading + java, not working for second execution
I am creating multiple threads from a timertask, and everything is working fine for first execution of timertask. 我正在从一个计时器任务创建多个线程,并且一切对于首次执行计时器任务都工作正常。 But when timertask is executed for second time,Thread.start() is not invoking run() method. 但是当第二次执行timertask时,Thread.start()不会调用run()方法。 I have tried every option I came across on internet,but nothing works. 我尝试了在互联网上遇到的所有选项,但没有任何效果。 Can anyone please help me !!! 谁能帮帮我吗 !!! :( :(
This is how I schedule timertask: 这是我安排timertask的方式:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new orderProcessScheduler(), getDate(), interval_period);
Here's the timerTask: 这是timerTask:
public class orderProcessScheduler extends TimerTask{
public void processOrders()
{
try
{
int totalThreads = 10;
List<orderThreadImpl> threadPool = new ArrayList<orderThreadImpl>();
for(int i = 0;i<totalThreads;i++)
{
threadPool.add(new orderThreadImpl());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
processOrders();
}
}
Here's thread implementation: 这是线程实现:
public class orderThreadImpl implements Runnable{
private Thread t;
@Override
public void run() {
// TODO Auto-generated method stub
try
{
// code for what this thread is suppose to do
}
catch(Exception e)
{
e.printStackTrace();
}
}
public orderThreadImpl()
{
this.t = new Thread(this);
t.start();
}
Here is what you should do, use an executor service thread pool to manage your threads, and start each thread for you : 这是您应该执行的操作,使用执行程序服务线程池来管理您的线程,并为您启动每个线程:
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TimerTaskQuestion {
public static void main(String[] args) {
OrderProcessScheduler orderScheduler = new OrderProcessScheduler();
Timer timer = new Timer();
timer.schedule(orderScheduler, 500, 1000);
}
public static class OrderProcessScheduler extends TimerTask {
private ExecutorService ex;
public OrderProcessScheduler() {
this.ex = Executors.newFixedThreadPool(10);
try {
this.ex.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
System.out.println("Number of active thread : " + ((ThreadPoolExecutor)this.ex).getActiveCount());
this.ex.execute(new orderThreadImpl());
}
public void initiateShutdown(){
this.ex.shutdown();
}
}
public static class orderThreadImpl implements Runnable {
@Override
public void run() {
try {
System.out.println("Executed from : " + Thread.currentThread().getName());
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.