//private final static Executor executor = Executors.newCachedThreadPool();// 启用多线程
private final static ExecutorService executor = Executors.newFixedThreadPool(5);//创建5个线程
public void test(){
long startTime = System.currentTimeMillis();
for (int i = 0; i < 50; i++) {
final int j = i;
executor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500);
System.out.println("*************" + j +"***"+ Thread.currentThread().getName());
} catch (Exception e) {
}
}
});
}
executor.shutdown();
System.out.println("======程序开始启动,我就会执行=====");
while(true){
if(executor.isTerminated()){
long end = System.currentTimeMillis();
System.out.println("======线程全部结束执行=====耗时:" + (end - startTime) + "ms" );
break;
}
}
}
运行结果:
======程序开始启动,我就会执行=====
*************4***pool-1-thread-5
*************0***pool-1-thread-1
*************3***pool-1-thread-4
*************2***pool-1-thread-3
*************1***pool-1-thread-2
*************5***pool-1-thread-5
*************6***pool-1-thread-1
*************7***pool-1-thread-4
*************8***pool-1-thread-3
*************9***pool-1-thread-2
*************12***pool-1-thread-4
*************11***pool-1-thread-1
*************10***pool-1-thread-5
*************14***pool-1-thread-2
*************13***pool-1-thread-3
*************18***pool-1-thread-2
*************19***pool-1-thread-3
*************15***pool-1-thread-4
*************16***pool-1-thread-1
*************17***pool-1-thread-5
*************20***pool-1-thread-2
*************22***pool-1-thread-4
*************23***pool-1-thread-1
*************24***pool-1-thread-5
*************21***pool-1-thread-3
*************28***pool-1-thread-5
*************27***pool-1-thread-1
*************26***pool-1-thread-4
*************29***pool-1-thread-3
*************25***pool-1-thread-2
*************33***pool-1-thread-3
*************30***pool-1-thread-5
*************31***pool-1-thread-1
*************32***pool-1-thread-4
*************34***pool-1-thread-2
*************36***pool-1-thread-5
*************37***pool-1-thread-1
*************38***pool-1-thread-4
*************35***pool-1-thread-3
*************39***pool-1-thread-2
*************40***pool-1-thread-5
*************41***pool-1-thread-1
*************42***pool-1-thread-4
*************43***pool-1-thread-3
*************44***pool-1-thread-2
*************48***pool-1-thread-3
*************45***pool-1-thread-5
*************46***pool-1-thread-1
*************47***pool-1-thread-4
*************49***pool-1-thread-2
======线程全部结束执行=====耗时:5003ms