java线程
继承Thread类
继承
Thread类,然后复写run()方法,直接new,然后start()
class Th1 extends Thread {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId());
}
}
Thread thread1=new Th1();
thread1.start();
实现Runnable接口
实现
Runnable接口,复写run(),new一个Thread(target),target是Runnable,然后start()
class Th2 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId());
}
}
Thread thread1 = new Thread(new Th2());
thread1.start();
实现Callable接口
实现
Callable接口,复写call()接口,call可以有返回值,然后使用FutureTask包装
class Th3 implements Callable<String> {
@Override
public String call(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId());
return "i am result";
}
}
FutureTask<String> futureTask = new FutureTask<>(new Th3());
new Thread(futureTask).start();
String result = futureTask.get(3, TimeUnit.SECONDS);
System.out.println(result);
使用线程池ThreadPoolExecutor
Executors是一个Java中的工具类 ,阿里巴巴代码规范中禁止使用,因为LinkedBlockingQueue如果不设置大小,它的大小就是int最大值,这样就造成OOM
BlockingQueue是用来存放还未执行的任务的队列
我们使用
ThreadPoolExecutor
ThreadPoolExecutor参数解释
- corePoolSize: 线程池的基本大小,即在没有任务需要执行的时候线程池的大小,并且只有在工作队列满了的情况下才会创建超出这个数量的线程。
- maximumPoolSize: 线程池中允许的最大线程数.线程池创建之后,可以调用
setMaximumPoolSize()修改 - keepAliveTime: 空闲线程等待工作的超时时间
- unit:keepAliveTime参数的时间单位
- workQueue: 存放任务的队列,注意这里要设置大小,不然又OOM
- threadFactory: 线程工厂
- RejectedExecutionHandler:线程拒绝策略
使用方式
- 实现
Runable或者Callable - 创建线程池,注意这里的参数配置
- 添加任务到线程池,这里可以使用
submit(),参数是第一步的Runable或者Callable,如果使用Runable,可以在第二个参数(可选参数)添加一个结果 - 获取执行结果(如果没设置返回结果就没必要做这一步),使用
get(),注意此操作是阻塞的 - 关闭线程池,这里有两个方法
shutdownNow()和shutdown(),shutdown()会阻止添加任务,阻止未开始的任务执行,并且等正在执行的任务完成后,关闭线程池;shutdownNow()会阻止添加任务,阻止未开始的任务执行并且尝试中断所有线程,可能会抛出异常.
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
3,
10,
60L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10));
// Future<?> submit = threadPoolExecutor.submit(new Th2(),"我是Th2的结果");
Future<?> submit = threadPoolExecutor.submit(new Th3());
// 获取结果
System.out.println(submit.get());
//关闭线程池
threadPoolExecutor.shutdown();
你要是觉得写的还不错,就点个关注,可以评论区留下足迹,以后方便查看.
你要是觉得写的很辣鸡,评论区欢迎来对线!
欢迎转载!

浙公网安备 33010602011771号