线程池的概念:
线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理。当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程对象所带来的性能开销,节省了系统的资源。
复制收展Javapackage com.nstc.bizflow.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @Desc 线程池
* @Author luolei
* @Date 2023/03/06 14:46
*/
public class ThreadPoolTest {
public static void main(String[] args) {
new ThreadPoolTest().execute();
}
public void execute(){
/**
* 设定线程池中最大500个线程
*/
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
final List<Future> threadList = new ArrayList<Future>();
for (int i = 0; i < 10; i++) {
String name = "线程"+i;
Future future = fixedThreadPool.submit(new MyCallable(name));
System.out.println("提交线程:"+name);
threadList.add(future);
}
/**
* Future
* 1、cancel():取消一个任务,并返回取消结果。参数表示是否中断线程
* 2、isCancelled():任务是否取消成功
* 3、isDone():判断当前任务是否执行完毕,包括正常执行完毕、执行异常或者任务取消
* 4、get():获取任务执行结果,任务结束之前会阻塞
* 5、get(long count,TimeUnit):在指定时间内尝试获取执行结果。若超时则抛出超时异常
*/
/**设置线程超时时间,遍历任务结果。**/
for (Future future : threadList) {
final Future futureTemp = future;
Thread t = new Thread(new Runnable() {
public void run() {
try {
System.out.println("线程超时时间为3秒...");
Object result = futureTemp.get(3000, TimeUnit.MILLISECONDS);
System.out.println("得到返回:"+result);
System.out.println("处理返回结果...");
} catch (TimeoutException e) {
System.out.println(Thread.currentThread().getName()+"超时...");
futureTemp.cancel(true);
} catch (Exception e){
e.printStackTrace();
futureTemp.cancel(true);
}
}
});
t.start();
}
/**结束线程池**/
fixedThreadPool.shutdown();
}
class MyCallable implements Callable{
String name;
public MyCallable(String name) {
this.name = name;
}
@Override
public Object call() throws Exception {
System.out.println(name + "【"+ Thread.currentThread().getName() + "】正在执行...开始时间:"+System.currentTimeMillis());
/**业务代码**/
Thread.sleep(3000);
System.out.println(name + "【"+ Thread.currentThread().getName()+"】已经结束...结束时间:"+System.currentTimeMillis());
return name+"【"+Thread.currentThread().getName()+"】"+System.currentTimeMillis();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82