使用ExecutorService-java进行线程化

时间:2015-11-22 06:16:33

标签: java multithreading

如您所见,我有两个类WorkerThread和ThreadPool。我试图在初始延迟3秒后执行workerthread任务,然后在延迟3秒之后执行相同的任务。我使用了schedulewithfixedelay& scheduleAtfixedRate并且它第一次等待但不是第二次等待。我是高级线程编程的新手,所以任何人都可以在下面的代码中帮助我解决我的错误,或者是否有任何替代类来完成任务。

class WorkerThread implements Runnable {

    private String command;

    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
        processCommand();
        try {
            System.out.println("Doing a task during : " + command + " - Time - " + new Date());
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName()+" End.");
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}


  public class ThreadPool {
      public static int times=0;
 public static ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    public static void main(String[] args) 
    {

        WorkerThread worker = new WorkerThread("proud"); 
       int i=0;
        while(i<2)
        {
        System.out.println(i);

        executor.scheduleAtFixedRate(worker, 3, 3, TimeUnit.SECONDS);
        i++;
        }

输出:

pool-1-thread-2 Start. Command = proud//waits for 3 seconds
pool-1-thread-1 Start. Command = proud//does not wait (for 3 seconds) to execute the same task 
Doing a task during : proud - Time - Sat Nov 21 18:10:56 EST 2015
pool-1-thread-1 End.
Doing a task during : proud - Time - Sat Nov 21 18:10:56 EST 2015
pool-1-thread-2 End.

0 个答案:

没有答案