如果主线程不需要一直循环,子线程池可以使用ThreadFactory setDaemon true 实现
主线程一直开启解决办法,上代码
@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());
为什么主线程需要休眠,不休眠,子线程池中如果线程在休眠,挂起,就会报
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)