If the main thread does not need to loop all the time, the child thread pool can be implemented using ThreadFactory setDaemon true
The main thread has been open solution, the code
@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());
Why does the main thread need to sleep and not sleep? If the thread in the child thread pool is sleeping or hangs, it will report
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.ars.team.tasks.config.ThreadTest.run(ThreadTest.java:26)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)