线程池
1.工作任务类
public class WorkTask implements Runnable {
@Override
public void run() {
try {
int r = (int)(Math.random()*10);
Thread.sleep(r*1000);
System.out.println(Thread.currentThread().getId() + " is over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2.创建无限多线程池方式:
public class CachedThreadPoolTest {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for ( int i = 0; i < 20; i++ ) {
exec.execute(new WorkTask());
}
// shutdown():不会立即终止线程池,而是要等所有任务缓存队列中的任务都执行完后才终止,但再也不会接受新的任务
exec.shutdown();
}
}
3.创建一定数量的线程池方式:
public class FixedThreadPoolTest {
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(3);
for ( int i = 0; i < 20; i++ ) {
exec.execute(new WorkTask());
}
exec.shutdown();
}
}
4.创建一个线程的线程池方式:
public class SingleThreadExecutorTest {
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for ( int i = 0; i < 20; i++ ) {
exec.execute(new WorkTask());
}
exec.shutdown();
}
}