TimerTask + multiThreading + java,不用于第二次执行

时间:2016-03-01 14:15:13

标签: java multithreading timertask

我正在从timertask创建多个线程,并且一切正常,以便首次执行timertask。但是当第二次执行timertask时,Thread.start()不会调用run()方法。我尝试过在互联网上遇到的每一个选项,但没有任何作用。谁能帮帮我吗 !!! :(

这就是我安排timertask的方式:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new orderProcessScheduler(), getDate(), interval_period);

这是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();
}
}

这是线程实现:

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();
}

1 个答案:

答案 0 :(得分:1)

这是您应该做的,使用执行程序服务线程池来管理您的线程,并为您启动每个线程:

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();
            }
        }
    }
}