将超时设置为线程类

时间:2011-02-09 15:28:51

标签: java android multithreading

HY !!

我有一个线程类,想要在10秒后设置一个超时。

这是怎么做到的?

类别:

public class HttpConnection extends Thread{

    List<NameValuePair> list;
    String url;
    Handler handler;

public HttpConnection(List<NameValuePair> params, String url, Handler handler) {

    this.list = params;
    this.url = url;
    this.handler = handler;
 }
@Override
public void run() {
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        String result;
        BufferedReader in = null;


                httppost.setEntity(new UrlEncodedFormEntity(this.list));



            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            if(response != null){
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                Message msg = Message.obtain();

                if ((result = sb.toString()) != null)
                {

                    msg.obj = result;   

                }
                else
                {
                    msg.obj = null;
                    throw new Exception("ERROR");
                }
                handler.sendMessage(msg); 
            }
    }
    catch (Exception e)
    {
      Log.e("XXX", e.getMessage());
    }

    super.run();
}


}

4 个答案:

答案 0 :(得分:3)

httpclient.getParams().setParameter("http.socket.timeout", 10000);//10 seconds

httpconnection将在10秒内超时,可能会抛出一些异常,在这种情况下你可以结束你的线程

答案 1 :(得分:2)

在Java中,您应该能够使用ThreadPoolExecutor的awaitTermination方法来设置超时。无论哪个类创建并执行此线程,都应该能够在执行程序上调用awaitTermination 10秒钟。这是你要做的事情(设置超时 ON WITHIN 你的线程)?

threadPoolExecutor.awaitTermination(10, TimeUnit.SECONDS);

答案 2 :(得分:0)

我可能不确定我们是否可以使用线程处理程序来完成这些任务,你最好为此目的使用异步任务,因为它依赖于互联网强度可用性,从服务器获取响应可能需要更多时间,所以请通过开发人员.android.com用于此主题。

答案 3 :(得分:-1)

super.run();

handler.postDelayed(this, 10000);

希望有所帮助。