Home  >  Article  >  Java  >  Using Java’s Worker class for background task processing

Using Java’s Worker class for background task processing

WBOY
WBOYforward
2023-04-20 22:34:211335browse

Explanation

1. Worker is the internal class of ThreadPoolexecutor, which is mainly used to maintain the interrupt control state of thread execution tasks.

2. Inherit AQS while implementing the Runnable interface. Implementing the Runnable interface means that the Worker is a thread.

Example

    private final class Worker
      extends AbstractQueuedSynchronizer
      implements Runnable{
        /**
         * This class will never be serialized, but we provide a
         * serialVersionUID to suppress a javac warning.
         */
        private static final long serialVersionUID = 6138294804551838833L;
 
        /** Thread this worker is running in.  Null if factory fails. */
       // 执行任务的线程
        final Thread thread;
        /** Initial task to run.  Possibly null. */
       // 执行的任务
        Runnable firstTask;
        /** Per-thread task counter */
        volatile long completedTasks;
 
        /**
         * Creates with given first task and thread from ThreadFactory.
         * @param firstTask the first task (null if none)
         */
        Worker(Runnable firstTask) {
          // 新建线程的时候,设置state -1 是为了防止线程还未执行时(线程只有在执行的时候才会被中断),就被     // 其它线程显式调用shutdown方法中断了,因为中断是要判断state大于等于0才会中断
          setState(-1);
          this.firstTask = firstTask;
          // 新建了一个线程
          this.thread = getThreadFactory().newThread(this);
        }
 
        /** Delegates main run loop to outer runWorker  */
        public void run() {
            runWorker(this);
        }

The above is the detailed content of Using Java’s Worker class for background task processing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete