线程池

1.工作任务类

  1. public class WorkTask implements Runnable {
  2. @Override
  3. public void run() {
  4. try {
  5. int r = (int)(Math.random()*10);
  6. Thread.sleep(r*1000);
  7. System.out.println(Thread.currentThread().getId() + " is over");
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }

2.创建无限多线程池方式:

  1. public class CachedThreadPoolTest {
  2. public static void main(String[] args) {
  3. ExecutorService exec = Executors.newCachedThreadPool();
  4. for ( int i = 0; i < 20; i++ ) {
  5. exec.execute(new WorkTask());
  6. }
  7. // shutdown():不会立即终止线程池,而是要等所有任务缓存队列中的任务都执行完后才终止,但再也不会接受新的任务
  8. exec.shutdown();
  9. }
  10. }

3.创建一定数量的线程池方式:

  1. public class FixedThreadPoolTest {
  2. public static void main(String[] args) {
  3. ExecutorService exec = Executors.newFixedThreadPool(3);
  4. for ( int i = 0; i < 20; i++ ) {
  5. exec.execute(new WorkTask());
  6. }
  7. exec.shutdown();
  8. }
  9. }

4.创建一个线程的线程池方式:

  1. public class SingleThreadExecutorTest {
  2. public static void main(String[] args) {
  3. ExecutorService exec = Executors.newSingleThreadExecutor();
  4. for ( int i = 0; i < 20; i++ ) {
  5. exec.execute(new WorkTask());
  6. }
  7. exec.shutdown();
  8. }
  9. }