一个无限等待的线程,类似于线程池中的核心线程

中断线程的方法

public void run() {

    //只要没有关闭,则一直不结束该线程

    while (!isShutDown) {

        isIdle = false;

        if (null != target) {

            //执行任务,注意这里调用的是run(),而不是start()

            target.run();

        }

        //任务结束,闲置状态

        isIdle = true;

        try {

            threadPool.repool(JThread.this);

            synchronized (this) {

                //线程空闲,等待新的任务到来

                wait();

            }

        } catch (InterruptedException e) {

        }

        isIdle = false;

    }

}

public synchronized void setTarget(Runnable target) {

    this.isShutDown = false;

    this.target = target;

    //设置任务之后,通知run方法,开始执行任务

    notifyAll();

}

/**

 * 关闭线程

 */

public synchronized void shutDown() {

    this.isShutDown = true;

   notifyAll();

}

}

你可能感兴趣的:(一个无限等待的线程,类似于线程池中的核心线程)