java-线程并发库-线程池
线程池是java5的新特性,用来管理线程
public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
/**创建线程池,固定一次执行三个任务 */
// ExecutorService threadPool = Executors.newFixedThreadPool(3);
/**创建线程池,非固定,来几个执行几个 */
// ExecutorService threadPool = Executors.newCachedThreadPool();
/**创建线程池,只执行单线程,但线程结束后马上重新同一个 */
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int j=0;j<10;j++){
final int task = j;
threadPool.execute(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +
" is looping " + i + ",task " + task);
}
}
});
}
threadPool.shutdown();
}
}
浙公网安备 33010602011771号