ThreadFactory && Thread

 
public class ThreadFactoryDemo {

  public static class MyThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
      return new WorkerThread(r);
    }
  }

  public static class WorkerThread extends Thread {
    private Runnable target;

    public WorkerThread(Runnable target) {
      this.target = target;
    }

    @Override
    public void run() {
      target.run();
      System.out.println("Thread-" + Thread.currentThread().getId());
    }
  }

  public static class Task implements Runnable {

    @Override
    public void run() {
      System.out.println("run task");
    }
  }

  public static void main(String[] args) throws InterruptedException {
    ExecutorService executorService = Executors.newCachedThreadPool(new MyThreadFactory());

    for(int i = 0; i < 10; i++) {
      executorService.execute(new Task());
    }
    executorService.shutdown();
    Thread.sleep(5000L);
  }
}

 

posted @ 2021-03-17 22:52  静静地挖坑  阅读(66)  评论(0)    收藏  举报