我需要一个java线程池的例子,比如说我设置线程池最大线程数为20
发布网友
发布时间:2022-05-11 00:03
我来回答
共1个回答
热心网友
时间:2023-12-10 01:19
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
ExecutorService exe = Executors.newFixedThreadPool(5);
for (int i = 1; i <= 50; i++)
{
exe.execute(new SubThread(i));
}
System.out.println("shutdown");
exe.shutdown();
while (true)
{
if (exe.isTerminated())
{
System.out.println("结束了!");
break;
}
Thread.sleep(200);
}
}
}
public class SubThread extends Thread
{
private final int i;
public SubThread(int i)
{
this.i = i;
}
@Override
public void run()
{
System.out.println(i);
try
{
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}