线程
创建线程的三种方法
1.继承Thread类创建线程
2.实现Runnable接口创建线程
3.实现Callable接口创建线程,重写call()方法
public class Main {
public static void main(String[] args) throws Exception {
// 将Callable包装成FutureTask,FutureTask也是一种Runnable
MyCallable callable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
// get方法会阻塞调用的线程
Integer sum = futureTask.get();
System.out.println(Thread.currentThread().getName() + Thread.currentThread().getId() + "=" + sum);
}
}
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100000; i++) {
sum += i;
}
Thread.sleep(5000);
return sum;
}
}
三种方式比较:
- Thread: 继承方式, 不建议使用, 因为Java是单继承的,继承了Thread就没办法继承其它类了,不够灵活
- Runnable: 实现接口,比Thread类更加灵活,没有单继承的限制
- Callable:
Thread和Runnable都是重写的run()方法并且没有返回值,Callable是重写的call()方法并且有返回值并可以借助FutureTask类来判断线程是否已经执行完毕或者取消线程执行 - 当线程不需要返回值时使用Runnable,需要返回值时就使用Callable,一般情况下不直接把线程体代码放到Thread类中,一般通过Thread类来启动线程
- Thread类是实现Runnable,Callable封装成FutureTask,FutureTask实现RunnableFuture,RunnableFuture继承Runnable,所以Callable也算是一种Runnable,所以三种实现方式本质上都是Runnable实现
sleep(): 睡眠指定时间,即让程序暂停指定时间运行,时间到了会继续执行代码,如果时间未到就要醒需要使用interrupt()来随时唤醒
interrupt(): 唤醒正在睡眠的程序,调用interrupt()方法,会使得sleep()方法抛出InterruptedException异常,当sleep()方法抛出异常就中断了sleep的方法,从而让程序继续运行下去
————————————————
版权声明:以上为CSDN博主「vbirdbest」的原创文章
原文链接:https://blog.csdn.net/vbirdbest/article/details/81282163
线程池
创建的四种方式,推荐第四种;
//核心为0,非核心:Max
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
//核心:10,非核心:0,
ExecutorService cachedThreadPool2 = Executors.newFixedThreadPool(10);
//核心:1
ExecutorService cachedThreadPool3 = Executors.newSingleThreadExecutor();
//核心:10,总数(核心+非核心):30,0L:时间,队列:10
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 30, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
work优先往核心里放,然后是队列,最后是非核心。
参数
corePoolSize:核心线程池的线程数量
maximumPoolSize:最大的线程池线程数量
keepAliveTime:线程活动保持时间,线程池的工作线程空闲后,保持存活的时间。
unit:线程活动保持时间的单位。
workQueue:指定任务队列所使用的阻塞队列
threadFactory :线程工厂