FutureTaskは完全な例を使用しています.

3021 ワード

MainActivityは以下の通りです
package cc.cv;

import java.util.concurrent.FutureTask;
import android.os.Bundle;
import android.app.Activity;
/**
 * Demo  :
 * FutureTask      
 * 
 * FutureTask   Runnable   ,   Thread            
 * 
 *     :
 * 1      Callable     CallableImpl,      call()  
 * 2   FutureTask   CallableImpl   
 * 3       FutureTask   ,     
 * 
 *           CallableImpl  ()  .
 *          futureTask.isDone()              
 *          futureTask.get()           ,          call()     .
 *     FutureTask      Thread      
 * 
 *     :
 * 1 http://uule.iteye.com/blog/1539084
 * 2 http://lf6627926.iteye.com/blog/1538313
 * 3 http://blog.csdn.net/kaiwii/article/details/6773971
 * 
 */
public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		testFatureTask();
	}

	private void testFatureTask(){
		try {
			CallableImpl callableImpl=new CallableImpl();
			FutureTask<Integer> futureTask=new FutureTask<Integer>(callableImpl);
			
			//          
			new Thread(futureTask).start();
			System.out.println("       ");
			
			//                  
			while(!futureTask.isDone()){
				System.out.println("                   ");
				System.out.println("           ...........");
			}
			
			//               
			System.out.println("       ,  :"+futureTask.get());
			
		} catch (Exception e) {
			
		}
	}

}
CallableImplは以下の通りです.
package cc.cv;

import java.util.concurrent.Callable;

public class CallableImpl implements Callable<Integer> {
	private final int COUNTER = 9527;

	public CallableImpl() {

	}

	@Override
	public Integer call() throws Exception {
		try {
			System.out.println("...           ...    :"+ Thread.currentThread().getName());
			Thread.sleep(1000 * 5);
			System.out.println("...           ...    :"+ Thread.currentThread().getName());
			Thread.sleep(1000 * 7);
			System.out.println("...           ...    :"+ Thread.currentThread().getName());
		} catch (Exception e) {
			
		}
		return COUNTER;
	}

}
main.xmlは以下の通りです
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>