【问题标题】:Java - url.openStream cannot work with multi-threadJava - url.openStream 不能与多线程一起使用
【发布时间】:2014-09-12 07:40:02
【问题描述】:

当我尝试从 url 读取 json text 时,这是一个明显的问题。我在URLReadermain 函数中进行了测试,它可以很好地返回文本。但是当我在线程中调用类外的方法时,IDE 没有报告任何Exceptions 也没有消息,直到我追溯到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 中总是可以正常工作。例如,这会导致&lt;html&gt; 文本:

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

编辑:

我提醒,在线程t1t2 中我调用了System.exit(0);,这导致进程不仅退出了线程。

【问题讨论】:

  • 我不知道这是否与您的问题有关,但在您的 Runnable 中,您发现了一个异常并且没有对它做任何事情。
  • 我在课堂上没有看到对loadText() 的任何呼叫Update
  • @ortis Ticker.last() 根据 json 文本返回一个 Double 值。我在这里不能太明确。
  • @knh170 你需要给我们看API.Ticker.last()的代码。
  • @manouti 我有几个线程调用与Thread t 并行。当我评论t1.start(); t2.start(); ..这一行并不管t.start();时,它运行得很顺利。

标签: java


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2020-09-03
    相关资源
    最近更新 更多