自定义线程工厂JAVA

该博客介绍了一个名为`MyThreadFactory`的自定义线程工厂类,它用于创建具有特定名称的线程。`MyAppThread`是线程的扩展,增加了线程生命周期的日志记录和异常处理。当线程运行结束时,会记录相关信息。
public class MyThreadFactory implements ThreadFactory{
  private final String poolName;

  public MyThreadFactory(String poolName){
    this.poolName = poolName;
  }

  ppublic Thread newThread(Runnable runnable){
    return new MyAppThread(runnable,poolName);
  }

}

public class MyAppThread extends Thread{
  public static final String DEFAULT_NAME = "MyAppThread";
  private static volatile boolean debugLifecycle = false;
  private static final AtomicInteger created = new AtomicInteger();
  private static final AtomicInteger alive = new AtomicInteger();
  private static final Logger log = Logger.getAnonymousLogger();

  public MyAppThread(Runnable runnable){
    this(runnable,DEFAULT_NAME);
  }

  public MyAppThread(Runnable runnable,String name){
    super(runnable,name+"-"+created.incrementAndGet());
    setUncaughtExceptionHandler{
      new Thread.UncaughtException(Thread t,Throwable e){
        log.log(Level.SEVERE,"UNCAUGHT IN the");
      }
    }
  }
  

  public void run(){
    boolean dubug = debugLifcycle;
    try{
      alive.incrementAndGet();
      super.run();
    }finally{
      alive.decrementAndGet();
      if(){
         log.log();      
      }
    }
  }
}
Java中,自定义线程线程大小通常涉及到线程池的配置,因为使用线程池能更好地管理线程资源。可以通过`ThreadPoolExecutor`类来创建自定义线程池,并且可以指定核心线程数量、最大线程数量等参数,从而实现对线程大小的自定义。以下是一个示例代码: ```java import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolDemo { public static void main(String[] args) { /* ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 核心线程数量, 最大线程数量, 空闲线程最大存活时间, 时间单位, 任务队列, 创建线程工厂, 任务的拒绝策略 ); 参数一:核心线程数量,不能小于0 参数二:最大线程数量,不能小于0,最大数量 >= 核心线程数量 参数三:空闲线程最大存活时间,不能小于0 参数四:时间单位,用TimeUnit指定 参数五:任务队列,不能为null 参数六:创建线程工厂,不能为null 参数七:任务的拒绝策略,不能为null */ ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 3, 6, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), java.util.concurrent.Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy() ); // 向线程池提交任务 for (int i = 0; i < 10; i++) { final int taskId = i; threadPoolExecutor.execute(() -> { System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task " + taskId + " is completed."); }); } // 关闭线程池 threadPoolExecutor.shutdown(); } } ``` 在上述代码中,通过`ThreadPoolExecutor`的构造函数自定义线程池的核心线程数量为3,最大线程数量为6,空闲线程最大存活时间为60秒,使用`ArrayBlockingQueue`作为任务队列,默认的线程工厂和`AbortPolicy`作为任务的拒绝策略 [^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值