Java 多线程/线程池的使用
1)下面的代码返回什么结果:
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,
50,
5,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(2),
new ThreadPoolExecutor.DiscardPolicy());
for(int i=0;i<10;i++){
final int task = i;
threadPoolExecutor.execute(() ->
{
System.out.println("thread is : "+ task);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
核心线程是3个,
最大线程数是50个,
核心线程满了后队列是能放2个,
任务是10个
实际能执行几个?
能执行8个 :第1到第3个核心线程执行;第4个,和第5个放队列中了,总是取不出来,不执行;第6到第10个新建队列执行,因为没有超过最大的限制50个。
thread is : 1
thread is : 0
thread is : 2
thread is : 5
thread is : 6
thread is : 7
thread is : 8
thread is : 9
2)下面的代码返回什么结果:
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,
5,
5,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(2),
new ThreadPoolExecutor.DiscardPolicy());
for(int i=0;i<10;i++){
final int task = i;
threadPoolExecutor.execute(() ->
{
System.out.println("thread is : "+ task);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
核心线程是3个,
最大线程数是5个,
核心线程满了后队列是能放2个,
任务是10个
实际能执行几个?
能执行5个 :第1到第3个核心线程执行;第4个,和第5个放队列中了,总是取不出来,不执行;第6到第7个新建队列执行,此时会达到最大限制5个;第8个到第10个,或根据策略丢弃。
thread is : 1
thread is : 0
thread is : 2
thread is : 5
thread is : 6
3)下面的代码返回什么结果:
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,
5,
5,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
new ThreadPoolExecutor.DiscardPolicy());
for(int i=0;i<10;i++){
final int task = i;
threadPoolExecutor.execute(() ->
{
System.out.println("thread is : "+ task);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
核心线程是3个,
最大线程数是5个,
核心线程满了后队列是能放100个,
任务是10个
实际能执行几个?
能执行3个 :第1到第3个核心线程执行;第4个到第10个都是放队列了,因为队列不满,是不会去触发创建其他线程的,就一直被放在队列中了,也取不出来。
thread is : 0
thread is : 1
thread is : 2
4)下面的代码返回什么结果:
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,
5,
5,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(5),
new ThreadPoolExecutor.DiscardPolicy());
for(int i=0;i<10;i++){
final int task = i;
threadPoolExecutor.execute(() ->
{
System.out.println("thread is : "+ task);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
核心线程是3个,
最大线程数是5个,
核心线程满了后队列是能放5个,
任务是10个
实际能执行几个?
能执行5个 :第1到第3个核心线程执行;第4个到第8个放队列中了,第9个到第10个,创建线程执行。
thread is : 2
thread is : 8
thread is : 0
thread is : 1
thread is : 9
参考:
Java线程池,阿里为什么不允许使用Executors?
为什么阿里发布的Java开发手册强制不允许线程池的创建使用Executors?
为什么阿里巴巴要禁用Executors创建线程池?
还没有评论,来说两句吧...