多线程学习(3):ScheduledExecutorService(newScheduledThreadPool) 与 Runnable接口实现

2018年7月9日14:13:06


【1】

使用参考:



【2】线程池

    /**
     * Creates a thread pool that can schedule commands to run after a
     * given delay, or to execute periodically.
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle.
     * @return a newly created scheduled thread pool
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }


【3】测试例子

WorkerThread.java:(实现Runnable接口的任务类)

package test01.SheduledThreadPoolExecutorTest;

import java.util.Date;

public 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 .Time = "+new Date());
		processCommand();
		System.out.println(Thread.currentThread().getName()+" End .Time = "+new Date());
	}
	
	private void processCommand(){
		try{
			Thread.sleep(5000);
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	
	public String toString(){
		return this.command;
	} 
}


SheduledThreadPoolExecutorTest.java:(线程池测试类)

package test01.SheduledThreadPoolExecutorTest;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SheduledThreadPoolExecutorTest {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
		
		System.out.println("Current Time = "+new Date());
		
		for(int i=0;i<3;i++){
			Thread.sleep(1000);
			WorkerThread worker = new WorkerThread("do heavy processing.");
			scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS);
		}
		
		Thread.sleep(10000);
		
		scheduledThreadPool.shutdown();
		while(!scheduledThreadPool.isTerminated()){
			//wait for all tasks to finish..
		}
		System.out.println("Finished all threads..");
	}

}


输出结果:   

Current Time = Thu Jul 12 09:20:09 CST 2018
pool-1-thread-1 Start .Time = Thu Jul 12 09:20:20 CST 2018
pool-1-thread-2 Start .Time = Thu Jul 12 09:20:21 CST 2018
pool-1-thread-3 Start .Time = Thu Jul 12 09:20:22 CST 2018
pool-1-thread-1 End .Time = Thu Jul 12 09:20:25 CST 2018
pool-1-thread-2 End .Time = Thu Jul 12 09:20:26 CST 2018
pool-1-thread-3 End .Time = Thu Jul 12 09:20:27 CST 2018
Finished all threads..

猜你喜欢

转载自blog.csdn.net/qq_29166327/article/details/80969318