1.线程池相关的类
2.重要类的api及其方法
Executors.newCachedThreadPool() 创建一个可缓存的线程池
Executors.newSingleThreadExecutor();创建一个只有一个线程执行的 不可修改的线程池
3.线程工厂ThreadFactory
就和我们平常使用的一样我们使用各种工厂类帮助我们创建线程,在Executors中我们使用Executors.defaultThreadFactory();静态方法来获得一个defaultThreadFactory类,先来看defaultThreadFactory的获得
Thread thread = threadFactory.newThread( new Runnable() {
public void run() {
}
});
使用newThread方法就可以不用再new thread来创建线程了
4.使用callable获得返回值
Callable和Runnbale一样代表着任务,区别在于Callable有返回值并且可以抛出异常
//使用callable<T>对象并且获取返回值和异常
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
Future<String> future = cachedThreadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return Thread.currentThread().getName();
}
});
try {
System.out.println("名称为"+future.get());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这里需要注意这里的get方法是同步执行的会阻塞主线程
异常捕获
public String call() throws Exception {
if(true){
throw new RuntimeException("抛出异常");
}
return Thread.currentThread().getName();
}
5.延迟执行
ScheduledExecutorService newCachedThreadPool = Executors.newScheduledThreadPool(3);
long millis = System.currentTimeMillis();
newCachedThreadPool.schedule(new Runnable() {
public void run() {
System.out.println(millis-System.currentTimeMillis());
}
}, 1000, TimeUnit.MILLISECONDS);
}
6.线程的关闭方法
newCachedThreadPool.shutdown(); 线程执行完成后关闭
newCachedThreadPool.shutdownNow();不等待线程执行完成 直接关闭
7.阻塞队列