简体   繁体   English

Java 线程立即终止

[英]Java threads get terminated instantly

I am trying to do some parallel http calls and database writing using threads in Java.我正在尝试使用 Java 中的线程进行一些并行 http 调用和数据库写入。 The roblem is that after calling thread.start() the thread does not call the run method but goes into TERMINATED state instantly.问题是在调用 thread.start() 之后,线程并没有调用 run 方法,而是立即进入 TERMINATED state。

while (fromIndex < list.size()) {
                final int toIndex = fromIndex + batchSize > list.size() ? list.size() : fromIndex + batchSize;
                fromIndex += batchSize;
                final int fromIndexCopy = fromIndex;
                threads[i] = new Thread() {
                    @Override
                    public void run(){
                        processConsumptionHistory(requestContext, list.subList(fromIndexCopy, toIndex), listFinished,
                                listFailed, listEnd);
                        markFailedUsage(listFailed);
                    }
                };
                threads[i].start();
                i++;
            }

            for (final Thread thread : threads) {
                thread.join();
            }

Why do threads not run?为什么线程不运行? Is there a better alternative?有更好的选择吗?

EDIT编辑

Threads do get started, the problem is that the lists passed are empty.线程确实开始了,问题是传递的列表是空的。

You probably wanted to reverse the order of these two statements:您可能想颠倒这两个语句的顺序:

fromIndex += batchSize;
final int fromIndexCopy = fromIndex;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM