使用Executors来创建线程池:
第一种:正常使用的线程池
public class ExecutorsTest implements Runnable{
private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ ":" + format.format(new Date()) + "执行");
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);//创建一个可重用的,具有2个线程数的线程池
pool.submit(new ExecutorsTest());//提交Runnabled实例
pool.submit(new ExecutorsTest());//提交Runnabled实例
}
}
本次运行的结果为:
pool-1-thread-2:14:07:00执行
pool-1-thread-1:14:07:00执行
从结果上可以看出两个线程运行的时间没有间隔。
第二种:使用线程池实现同步(创建线程池里只有一个线程数)
public class ExecutorsTest implements Runnable{
private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":" + format.format(new Date()) + "执行");
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);//创建一个可重用的,具有2个线程数的线程池
pool.submit(new ExecutorsTest());//提交Runnabled实例
pool.submit(new ExecutorsTest());//提交Runnabled实例
}
}
运行结果为:
pool-1-thread-1:14:10:20执行
pool-1-thread-1:14:10:23执行
从结果可以看出,两个结果运行时间相差了三秒,Thread.sleep(3000);就是这儿运行的费时时间。
看来线程池中只有一个线程数的时候,是可以实现同步效果的。