編輯:關於 Android 程式設計
接上文。
以前我對 Java 多線程的理解僅停留在實現 Runnable 接口或繼承 Thread 類、重寫 run() 方法、最後 start() 就算完事。但一旦涉及死鎖、對共享資源的訪問、隨時監控線程狀態與執行順序,以及獲取線程返回值等場景,就顯得力不從心了。
Callable 接口代表一段可以調用並返回結果的代碼;Future 接口則表示異步任務執行時的狀態、返回值等信息。所以說,Callable 用於產生結果,Future 用於獲取結果。
Callable 是一個接口,只包含一個 call() 方法,它是一個返回結果並可能拋出異常的任務。為便於理解,可以把 Callable 類比為 Runnable,而 call() 方法則類似於 run() 方法。源碼如下:
public interface Callable{ V call() throws Exception; }
Future 也是一個接口,用於表示異步計算的結果,提供了檢查計算是否完成、等待完成並獲取結果的方法。源碼如下:
public interface Future{ boolean cancel(boolean mayInterruptIfRunning); // 嘗試取消任務 boolean isCancelled(); // 是否已被取消 boolean isDone(); // 是否已完成 V get() throws InterruptedException, ExecutionException; // 獲取結果 V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; // 超時獲取結果 }
import java.util.concurrent.*;
class MyCallable implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) sum += i;
return Integer.valueOf(sum);
}
}
public class CallableTest1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newSingleThreadExecutor(); // 創建線程池
Callable c1 = new MyCallable(); // 創建有返回值的任務
Future f1 = pool.submit(c1); // 提交任務並獲取 Future
System.out.println(f1.get()); // 輸出結果
pool.shutdown(); // 關閉線程池
}
}
運行結果為 4950。
結果說明:在主線程 main 中,先通過 newSingleThreadExecutor() 新建線程池,接著創建 Callable 對象 c1,再通過 pool.submit(c1) 把它提交到線程池處理,並將返回結果保存到 Future 對象 f1 中;然後用 f1.get() 獲取結果,最後通過 pool.shutdown() 關閉線程池。
通過上面這個簡單的例子,我們完全可以把原本用 Runnable 或 Thread 實現的線程,改寫成 Callable 和 Future 的形式:
public class MainActivity extends Activity {
public static final String TAG = "webService_pj";
private EditText phoneSecEditText;
private TextView resultView;
private Button queryButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneSecEditText = (EditText) findViewById(R.id.phone_sec);
resultView = (TextView) findViewById(R.id.result_text);
queryButton = (Button) findViewById(R.id.query_btn);
queryButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String phoneSec = phoneSecEditText.getText().toString().trim();
if ("".equals(phoneSec) || phoneSec.length() < 7) {
phoneSecEditText.setError("您輸入的手機號碼(段)有誤!");
phoneSecEditText.requestFocus();
resultView.setText("");
return;
}
String nameSpace = "https://WebXml.com.cn/";
String methodName = "getMobileCodeInfo";
String endPoint = "https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
String soapAction = "https://WebXml.com.cn/getMobileCodeInfo";
ArrayList params = new ArrayList();
ArrayList
至此,在 Android 上調用 WebService 並獲取線程返回值的功能就完整實現了。
Android Tinyalsa 音頻介面解析
tinyalsa 位於 Android 源碼的 external/tinyalsa 位置。 關於 tinyalsa,它是 Google 在 Android 4.0 之後推
仿淘寶購物車:RecyclerView 巢狀勾選的全選邏輯實作
購物車的多選邏輯看起來簡單,實作起來卻容易漏 case:勾選店鋪要自動勾選店內所有商品、取消某個商品要讓店鋪變成半選或不選、底部全選框又必須同步反映全域狀態。本文用 Re
Android xmlns 命名空間是什麼?基本概念與自定義屬性實作
Android xmlns 的作用與自定義實例xmlns:android=https://schemas.android.com/apk/res/android 的作用如
九宮格手勢解鎖自定義 View 實作
效果說明這個自定義 View 的效果與手機常見的九點手勢解鎖類似。畫面中會出現九個點,使用者用手指依序滑過這些點,形成一組密碼,再進行驗證。實作思路整體實作可以拆成幾個部