Home > Java > javaTutorial > Using Java's Worker class for background task processing

Using Java's Worker class for background task processing

WBOY
Release: 2023-04-20 22:34:21
forward
1394 people have browsed it

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);
        }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template