单线程线程池
class threadPool{
public static void main(String[] args) {
long f = System.currentTimeMillis();
//-------------------------------------------
//创建线程池只有一个线程
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(new myR());
es.execute(new myR());
es.execute(new myR());
es.execute(new myR());
es.shutdown();
//-------------------------------------------
long h = System.currentTimeMillis();
System.out.println(h-f);
}
}
class myR implements Runnable{
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行了");
}
}
执行结果:
线程池只有一个线程 所有多个任务是排队进入
多线程线程池
带缓存的线程池
class threadPool{
public static void main(String[] args) throws InterruptedException {
long f = System.currentTimeMillis();
//-------------------------------------------
//创建线程池 带缓存的线程池
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
Thread.sleep(10*i);
es.execute(new myR());
}
es.shutdown();
//-------------------------------------------
long h = System.currentTimeMillis();
System.out.println(h-f);
}
}
class myR implements Runnable{
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行了");
}
}
执行结果
当有任务需要线程 线程池提供新建一个线程 如果有闲置的线程将会使用闲置的线程 最多新建 Integer.Max 个线程
指定线程个数的线程池
class threadPool{
public static void main(String[] args) throws InterruptedException {
long f = System.currentTimeMillis();
//-------------------------------------------
//创建线程池 指定个数
ExecutorService es = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
es.execute(new myR());
}
es.shutdown();
//-------------------------------------------
long h = System.currentTimeMillis();
System.out.println(h-f);
}
}
class myR implements Runnable{
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行了");
}
}
执行结果
当线程都在使用时 其他任务需要等待空出新线程
延迟执行线程的 线程池
class threadPool{
public static void main(String[] args) throws InterruptedException {
long f = System.currentTimeMillis();
//-------------------------------------------
//创建线程池可以更改数字 个数
//如果只需要一个可以 使用Executors.newSingleThreadScheduledExecutor();
ScheduledExecutorService es = Executors.newScheduledThreadPool(2);
for (int i = 0; i < 10; i++) {
// 参数: 线程 延迟时间 延迟单位
es.schedule(new myR(),1000, TimeUnit.MILLISECONDS);
//参数 : 线程 延迟时间 周期 延迟单位
es.scheduleAtFixedRate(new myR(),1000,1000, TimeUnit.MILLISECONDS);
}
//-------------------------------------------
long h = System.currentTimeMillis();
System.out.println(h-f);
}
}
class myR implements Runnable{
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行了");
}
}
执行结果
间隔 一秒 之后执行 任务