有没有办法判断一个连接是从超时还是线程死亡退出?

时间:2014-12-29 20:17:14

标签: java

我有一些与api对话的代码。服务器运行大约一天后,它会冻结对stream.read;

的调用

我决定把代码放在一个线程中。因此,如果线程超时,它将为api的返回值返回null。我找不到任何代码来告诉超时或线程死亡的连接退出

String GetBitrexApiThread(String url) {

    cThread cRun=new cThread();
    cRun.url=url;
    cRun.run();
    try {
        // wait 10 seconds to make api call
        cRun.join(1000*30);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // would like to return a null if thread timedout.
    return cRun.reply;    
}

// thread code
public class cThread extends Thread {
    String reply;
    String url;

    public void run() {
        try {

            URL myurl = new URL(url);
            System.out.println("Open connection");
            HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
            con.setConnectTimeout(15000);
            System.out.println("Get input stream");
            InputStream ins = con.getInputStream();
            System.out.println("Create reader");
            InputStreamReader isr = new InputStreamReader(ins);
            System.out.println("Creat buffer reader");
            BufferedReader in = new BufferedReader(isr);

            String inputLine;

            System.out.println("Read indata2");

            int t;
            while ((t= in.read()) != -1) {
                 // System.out.println("next read");
                 reply+=(char)t;;
                 // System.out.println(reply);
            }

            System.out.println("finish Read indata");
        } catch (Exception e) {
            System.out.println("Exception in getting data from API server");
            reply=null;
        }
    }
};

2 个答案:

答案 0 :(得分:2)

我假设您将run();替换为start();,否则您的后台任务将在当前主题中运行。

判断任务是否仍在运行的方法是调用thread.isAlive();您还需要以线程sfae方式传回结果并处理抛出的异常。

正如我评论的那样,ExecutorService会为您完成所有这些。

答案 1 :(得分:1)

Thread one = ...;
one.start();
one.join(5000);
if (one.isAlive()) {
  //clearly, the Thread is not dead
}