執行緒一
http://givemepass.blogspot.tw/2015/10/hello_90.htmlthread的使用方式
public class MyTask implements Runnable{
public void run(){
//execute your task
}
}
new Thread(new MyTask()).start();
執行緒二
http://givemepass-blog.logdown.com/posts/296942-how-to-use-the-thread-2//新建(尚未啟動的狀態)
new Thread(myRunnable);
//Runnable(進入可排程系統, 只要排程器(Scheduler)指派它給CPU執行, 則會開始執行run方法。)
new Thread(myRunnable).start();
flag 為一個Boolean值,讓flag == false 就可以停止Thread
new Thread(new Runnable(){
public void run(){
while(flag){
//task
}
}
}).start();
Thread thread = new Thread(new Runnable(){
public void run(){
try{
//task
} catch(InterruptExcetption e){
//handle exception
}
}
});
thread.start();
thread.interrupt();
當啟動Thread以後, 想要停止就呼叫Interrupt則會發出Exception來停止Thread。
如何使用Handler
http://givemepass-blog.logdown.com/posts/296606-how-to-use-a-handler//runOnUiThread幫你另開執行緒,結束ui後回到主要執行緒。
new Thread(new Runnable() {
public void run() {
//這邊是背景thread在運作, 這邊可以處理比較長時間或大量的運算
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
//這邊是呼叫main thread handler幫我們處理UI部分
}
});
}
}).start();
到這裡,你一定會疑惑handler的實質上到底幹嘛的,這時候就可以看這一篇。
Android 執行緒 - Thread 與 Handler
http://andcooker.blogspot.tw/2012/09/android-thread-handler.html其它很棒的延伸
如何使用HandlerThread
http://givemepass-blog.logdown.com/posts/296790-how-to-use-handlerthread
如何使用AsyncTask
http://givemepass-blog.logdown.com/posts/297108-how-to-use-asynctask
如何使用ThreadPool
http://givemepass-blog.logdown.com/posts/296960-how-to-use-the-threadpool
如何使用ThreadPool 來下載網路圖片
http://givemepass-blog.logdown.com/posts/289636-how-to-use-the-threadpool-to-download-pictures
當你上面全部看完之後,最後來幫你搞懂
如何了解Task、Thread、ThreadPool、Handler、Looper、Message、MessageQueue、AsyncTask
http://givemepass-blog.logdown.com/posts/297175-how-to-understand
簡易使用
new Handler().postDelayed(new Runnable(){
public void run(){
//處理少量資訊或UI
}
}, 3000);
new Thread(new Runnable() {
public void run() {
//這邊是背景thread在運作, 這邊可以處理比較長時間或大量的運算
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
//這邊是呼叫main thread handler幫我們處理UI部分
}
});
}
}).start();
//或者
view.post(new Runnable(){
public void run(){
//更新畫面
}
});
//又或者另外一種寫法
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case 1:
//處理少量資訊或UI
break;
}
}
};
new Thread(new Runnable(){
public void run(){
Message msg = new Message();
msg.what = 1;
mHandler.sendMessage(msg);
}
});
沒有留言:
張貼留言