2014-12-29 72 views
1

我有一些代碼與api交談。服務器運行了大約一天之後,它就凍結了對stream.read的調用;有沒有辦法判斷連接是否從超時或線程死亡退出?

我決定把代碼放在一個線程中。所以如果線程超時,它將爲api的返回值返回一個空值。我找不到,告訴如果加入出境的超時或線程死亡

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; 
     } 
    } 
}; 
+0

'Thread#run!= Thread#start' –

+0

另外,不要使用'join()'。使用'Future'或'CountDownLatch'或其他一些併發原語。 –

+0

我建議你使用一個ExecutorService來處理這類事情。如果你真的知道你在做什麼,只使用原始線程。 –

回答

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

任何代碼,我想你會取代run();start();否則你的後臺任務在當前線程中運行。

判斷任務是否仍在運行的方法是調用thread.isAlive();您還需要以線程方式傳回結果並處理拋出的異常。

正如我評論說,一個ExecutorService爲你做這一切。

相關問題