El subproceso principal de Java continúa ejecutándose y los subprocesos se cierran y reciclan manualmente

Si el subproceso principal no necesita repetir todo el tiempo, el grupo de subprocesos secundarios se puede implementar utilizando ThreadFactory setDaemon true

El hilo principal ha sido la solución abierta, el código

@NoArgsConstructor
public class ThreadTest implements Runnable {

    PyList pyList;
    boolean flag = true;
    public ThreadTest(PyList pyList){
        this.pyList = pyList;
    }

    @Override
    public void run() {
        while(flag){
            pyList.add(Py.newFloat(24.69));
            System.out.println("ThreadTest");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("结束");
    }

    public void shutdown(){
        this.flag = false;
    }
}

CustomizableThreadFactory threadFactory = new CustomizableThreadFactory("trend-iot-read-");
        ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 2, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1),threadFactory);

        PyObject[] data = {};
        PyList pyList = new PyList(data);

        ThreadTest threadTest = new ThreadTest(pyList);
        pool.execute(threadTest);


        for (int i = 0; i < 3; i++) {
            System.out.println(pyList.size()+"----------------------");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        threadTest.shutdown();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(pool.getActiveCount());
        pool.shutdownNow();
        System.out.println(pool.isShutdown());

¿Por qué el subproceso principal necesita dormir y no dormir?Si el subproceso en el grupo de subprocesos secundarios está durmiendo o se cuelga, informará

java.lang.InterruptedException: suspensión interrumpida
    en java.lang.Thread.sleep(Native Method)
    en com.ars.team.tasks.config.ThreadTest.run(ThreadTest.java:26)
    en java.util.concurrent.ThreadPoolExecutor. runWorker(Fuente desconocida)
    en java.util.concurrent.ThreadPoolExecutor$Worker.run(Fuente desconocida)
    en java.lang.Thread.run(Fuente desconocida)

Supongo que te gusta

Origin blog.csdn.net/zjy660358/article/details/126423109
Recomendado
Clasificación