gpt4 book ai didi

Java - url.openStream 无法使用多线程

转载 作者:行者123 更新时间:2023-12-01 12:32:54 26 4
gpt4 key购买 nike

当我尝试阅读 json text 时,这是一个明显的问题来自网址。我在URLReader中进行了测试的main函数它返回文本很好。但是当我在线程中调用类外部的方法时,IDE没有报告任何Exception也没有消息,直到我追溯到 URLReader .

public static String loadText(String path) throws Exception {

URL url = new URL(path);

try (BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()))) { /* <--- where it goes wrong */
String inputLine;
String lines = "";
while ((inputLine = in.readLine()) != null) {
lines += inputLine;
} return lines;
}
}

线路url.openStream()对线程的外部调用保持沉默,但奇怪的是,它总是在自己的main中正常工作。 。例如,这会导致 <html>文本:

public static void main(String[] args) throws Exception {
System.out.println(text("https://google.com"));
}

------------------------------------------------这里有一些代码--------- ------------------------------------------

线程看起来像:

Thread t = new Thread(new Runnable(){
public void run() {
try { Update.updateRecord(); }
catch (Exception e) {}
}
});

t.start();

可能是什么问题?

<小时/>

编辑:

manouti提到过,我有一些线程以及 Thread t 。当我离开时t.start();单独使用时,它工作得很好,但与其他线程一起使用时就不行。

Thread t1, t2, t;

/* defined runnable() here */
t1.start(); t2.start(); t.start(); // <--- went wrong

t.start(); // <--- perfectly

编辑:

我在线程 t1 中提醒了这一点和t2我打了System.exit(0); ,这导致进程退出,而不仅仅是线程退出。

最佳答案

显式问题是由另一个线程中的一行 System.exit(0); 引起的。

How a thread should close itself in Java?解释了如何退出线程,否则 exit(0) 将中断进程,而不仅仅是线程

关于Java - url.openStream 无法使用多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25803182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com