使用Executors创建有10个线程的线程池
package com.zr.demo01;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 使用Executors创建有10个线程的线程池,该线程池的线程都是待机状态,所以避免了开启新线程的时间
* @author ZR
*
*/
public class Seventeenth {
public static void main(String[] args) {
MyRunable myRunable=new MyRunable();
//有10个线程的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
//使用4个线程
service.submit(myRunable);
service.submit(myRunable);
service.submit(myRunable);
service.submit(myRunable);
//关闭线程池
service.shutdown();
}
}
class MyRunable implements Runnable{
private static int i=1;
@Override
public void run() {
while(true) {
synchronized (MyRunable.class) {
if (i<=100) {
System.out.println(Thread.currentThread().getName()+"------------------->"+i);
i++;
}else {
return;
}
}
}
}
}