>  기사  >  Java  >  백그라운드 작업 처리를 위해 Java의 Worker 클래스 사용

백그라운드 작업 처리를 위해 Java의 Worker 클래스 사용

WBOY
WBOY앞으로
2023-04-20 22:34:211299검색

설명

1. Worker는 ThreadPoolexecutor의 내부 클래스로, 주로 스레드 실행 작업의 인터럽트 제어 상태를 유지하는 데 사용됩니다.

2. Runnable 인터페이스를 구현하는 동안 AQS를 상속합니다. Runnable 인터페이스를 구현한다는 것은 Worker가 스레드라는 것을 의미합니다.

인스턴스

    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);
        }

위 내용은 백그라운드 작업 처리를 위해 Java의 Worker 클래스 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제