public class ThreadPool {
public static void main(String[] args) {
/*
//线程池
int corePoolSize = 2;
int maximumPoolSize = 5;
long keepAliveTime = 0;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(8);
// ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize,
// maximumPoolSize,
// keepAliveTime,
// unit,
// workQueue);
// for(int i=0;i<25;i++)
// pool.submit(new PrintThread());
// pool.shutdown();
//Rejection policy: abort
keepAliveTime = 30;
ThreadPoolExecutor pool2 = null;
try {
pool2= new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), new AbortPolicy());
for(int i=0 ;i<25;i++)
pool2.submit(new PrintThread());
}finally {
pool2.shutdown();
}
*/
//Single thread: execute one by one
// ExecutorService e = Executors.newSingleThreadExecutor();
/ / Executors.newSingleThreadExecutor(threadFactory);
// for(int i=0;i<10;i++) {
// e.execute(new PrintThread());
// }
// e.shutdown();
//fixed Thread pool: 3 worker threads
// ExecutorService e = Executors.newFixedThreadPool(3);
// for(int i=0;i<10;i++)
// e.execute(new PrintThread());
// e.shutdown();
//required Create as many threads as you want
// ExecutorService e = Executors.newCachedThreadPool();
// for(int i=0;i<1000;i++)
// e.execute(new PrintThread());
// e.shutdown() ;
//Scheduled task: single thread
// ScheduledExecutorService e = Executors.newSingleThreadScheduledExecutor();
// e.schedule(new PrintThread(), 10, TimeUnit.SECONDS); //execute once with a delay of 10 seconds
// e.schedule( new PrintThread(), 10, TimeUnit.SECONDS);
// e.scheduleWithFixedDelay(new PrintThread(), 2, 12, TimeUnit.SECONDS); //execute every 12 seconds
//timed task: three threads execute concurrently
ScheduledExecutorService e = Executors.newScheduledThreadPool(3);
for(int i=0;i<4;i++) e.scheduleWithFixedDelay(new PrintThread(), 2, 5, TimeUnit.SECONDS); //execute e
every 5 seconds
.scheduleAtFixedRate(new PrintThread(), 2, 6, TimeUnit.SECONDS); //execute every 6
}
static class PrintThread implements Runnable{
public void run() {
System.out.println("hello..");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}