醒醒吧!你沒有朋友
Image img = loadImg(url);//讀取圖片
refresh();//刷新畫面
new Thread(new Runnable(){
public void run(){
Image img = loadImg(url);//讀取圖片
refresh();//刷新畫面
}
}).start();
進行了一個更新畫面的動作
Runnable
Runnable
Handler
Handler
Message Queue
Looper
Message
Message
UI Thread
Message
爛透惹
givemepass
2016/10/29
new Thread(new Runnable(){
@Override
public void run(){
//Task 1
runOnUiThread(new Runnable(){
@Override
public void run(){
//update ui
new Thread(new Runnable(){
@Override
public void run(){
//Task 2
runOnUiThread(new Runnable(){
@Override
public void run(){
//update ui
}
});
}
}).start();
}
});
}
}).start();
科科
new Thread(new Runnable() {
public void run() {
Log.e(TAG, "A");
Looper.prepare();
new Handler().post(new Runnable(){
@Override
public void run() {
Log.e(TAG, "B1");
}
});
new Handler().post(new Runnable(){
@Override
public void run() {
Log.e(TAG, "B2");
Looper.myLooper().quit();
}
});
Looper.loop();
Log.e(TAG, "C");
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Log.e(TAG, "D");
}
});
}
}).start();
輸出為:
HandlerThread mHandlerThread = new HandlerThread("my handler thread");
mHandlerThread.start();
Handler mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(task1);
mHandler.post(task2);
// ... n-2 task
mHandler.post(taskN);
//...
mHandlerThread.quit();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
int corePoolSize,
int maxPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue
);
等待時間
這是一段非常耗時的程式
其他工作
其他工作
Call
Other Call
other call return
call return
Client
Service
Data
這是一段非常耗時的程式
其他工作
其他工作
Call
Other Call
other call return
立即返回
Client
Service
Data
Request
Client
Server
Future
Data
Thread
Real
Data
Result
Future Object
Interface Future<V>
All Known Implementing Classes:
ForkJoinTask, FutureTask, RecursiveAction,
RecursiveTask, SwingWorker
FutureTask(Callable<V> callable)
FutureTask(Runnable runnable, V result)
FutureTask<Void> futureTask = new FutureTask<>(()->{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hi");
}, null);
new Thread(futureTask).start();
try {
futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Object> future = executor.submit(new Callable<Object>(){
public Object call() throws Exception{
Object obj = doLongTask();
return obj;
}
});
Object result = future.get();
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorCompletionService<String> completionService =
new ExecutorCompletionService<>(executorService);
for(int i = 0; i < 100; i++) {
completionService.submit(getTask(i));
}
//...
String s = completionService.take().get();
class MyTask extends AsyncTask<Params, Progress, Result>{
protected void onPreExecute(){
// in main thread
}
protected Result doInBackground(Params... params){
// in background thread
}
protected void onProgressUpdate(Progress... progress){
// in main thread
}
protected void onPostExecute(Result result){
// in main thread
}
protected void onCancelled(Result result){
// in main thread
}
}
//循序
executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, Object... objs);
//並行
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Object... objs);
//自訂
executeOnExecutor(CustomExecutor, Object... objs);
初音只是個軟體
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
抓到!
ExecutorService singleThread = Executors.newSingleThreadExecutor();
singleThread.submit(new Runnable() {
@Override
public void run() {
//處理Task
runOnUiThread(new Runnable() {
@Override
public void run() {
//處理Ui
}
});
}
});
singleThread.submit(new Runnable() {
@Override
public void run() {
//處理Task
runOnUiThread(new Runnable() {
@Override
public void run() {
//處理Ui
}
});
}
});
readFileAsync(args[0],
content -> processContentAsync(content,
processedContent -> handleData(content,
c-> out.println(c) ,
ex -> ex.printStackTrace(), service) ,
ex -> ex.printStackTrace(), service),
ex -> ex.printStackTrace(), service);
CompletableFuture
.runAsync(() -> task1)
.thenRunAsync(() -> task2)
.thenRunAsync(() -> task3)
.whenComplete((r, ex) -> System.out.println("done"));
Android N 才能使用Java 8
List<Task> taskList = new ArrayList<>();
taskList.add(new Task("task 1"));
taskList.add(new Task("task 2"));
taskList.add(new Task("task 3"));
Observable.from(taskList)
.subscribe(new Observer<Task>() {
private boolean isTaskSuccess = true;
@Override
public void onCompleted() {
System.out.println("completed");
}
@Override
public void onError(Throwable e) {
System.out.println("error");
}
@Override
public void onNext(Task task) {
try {
if(!task.call() || !isTaskSuccess){
isTaskSuccess = false;
System.out.println(task.getName() + " failed.");
} else {
System.out.println(task.getName() + " success.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});