我也是剛剛接觸程序開發(fā),一個菜鳥。前面和幾個同學(xué)準(zhǔn)備做一個移動教務(wù)系統(tǒng),網(wǎng)上看了很多資料都說了對運行一些費時。如數(shù)據(jù)庫、網(wǎng)絡(luò)的鏈接操作,需要新開一個thread對其進行處理。但是后面在對程序進行調(diào)試的過程中,剛開始的時候報了空指針錯誤。根據(jù)錯誤提示,進行修改。說實話,經(jīng)過那個過程發(fā)現(xiàn)自己真的還很菜,排錯的經(jīng)驗太少了。直到過了好久才想到報了空指針錯誤,是因為在線程里生成的對象,因為有時間延遲,對于線程后面的對象來說是空的,所以才導(dǎo)致了空指針錯誤。后面參考的解決方法是利用join()函數(shù)。當(dāng)然也可用其他方法。
創(chuàng)新互聯(lián)公司專注于金壇企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站開發(fā),成都做商城網(wǎng)站。金壇網(wǎng)站建設(shè)公司,為金壇等地區(qū)提供建站服務(wù)。全流程按需定制,專業(yè)設(shè)計,全程項目跟蹤,創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)
下面寫的代碼:
public class MyThread extends Thread { private InputStream is = null; private String url; private String method; private Listparams; public MyThread(String url, String method, List params) { this.method = method; this.url = url; this.params = params; } public void run() { try { // check for request method if (method.equals("POST")) { // request method is POST // defaultHttpClient BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) HttpConnectionParams .setConnectionTimeout(httpParameters, 30000); // in milliseconds which is the timeout for waiting for // data. HttpConnectionParams.setSoTimeout(httpParameters, 30000); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); setIs(httpEntity.getContent()); } else if (method.equals("GET")) { BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) HttpConnectionParams .setConnectionTimeout(httpParameters, 30000); // in milliseconds which is the timeout for waiting for // data. HttpConnectionParams.setSoTimeout(httpParameters, 30000); // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); String temp_url = url + "?" + paramString; HttpGet httpGet = new HttpGet(temp_url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); setIs(httpEntity.getContent()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public InputStream getIs() { return is; } public void setIs(InputStream is) { this.is = is; } }
通過下面的語句對以上生成的對象(“setIs(httpEntity.getContent());
“)進行調(diào)用
MyThread myThread = new MyThread(url, method, params); myThread.start(); myThread.join();//同做join()函數(shù)對myThread進行處理,使其一般的對象那樣使用即可 is = myThread.getIs();//獲得is對象