ThreadUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import android.os.Handler;
import android.os.Looper;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
 
public class ThreadUtils {
 
    private static Handler sHandler = new Handler(Looper.getMainLooper());
 
    private static ExecutorService sExecutorService = Executors.newSingleThreadExecutor();
 
    //Runnable:任务,必须依附于某一个线程
    //Thread:线程,线程用来执行任务
    //Process:进程
    //保证r这个任务一定是在主线程中执行
    public static void runOnUiThread(Runnable r){
 
        if(Looper.myLooper() == Looper.getMainLooper()) {
            //主线程
            //new Thread(r).start(); 一旦new了Thread就一定是子线程
            r.run();
        } else {
            //new Thread(r).start()
            sHandler.post(r);
        }
 
        /*new Thread(new Runnable(){
            @Override
            public void run() {
 
            }
        }).start();*/
    }
 
    //保证r一定在子线程中得到执行
    public static void runOnSubThread(Runnable r) {
        //new Thread(r).start();
        //线程池的概念,线程池里面装的是线程,使用线程池可以达到线程的复用,提高性能
        sExecutorService.submit(r);//将r丢到线程池中,线程池中的线程就会来执行r这个任务
    }
}

 


posted on   LoaderMan  阅读(332)  评论(0编辑  收藏  举报

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示