Java线程和线程池

Android中创建线程的方式有,new Thread,new Thread(Runnable),new Thread(Callable)的形式。

A. 直接new Thread简单方便.

B. new Thread(Runnable)这种形式相比第一种更简单明了。

C. Callable相比于Runnable,在于它有返回值。

其适用的方式如下:

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
package com.fxb.threadtest;
 
import android.util.Log;
 
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
 
public class ThreadTest {
 
    public static void callableTest(){
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(1000);
                Log.i(MainActivity.TAG, "create by callable!");
                return 0;
            }
        };
        FutureTask<Integer> task = new FutureTask<Integer>(callable);
        new Thread(task, "mytask").start();
    }
 
    public static void threadTest(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                Log.i(MainActivity.TAG, "create by thread!");
            }
        }.start();
    }
 
    public static void runnableTest(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(MainActivity.TAG, "create by runnable!");
            }
        }).start();
    }
 
}

线程池能够对线程进行缓存和复用,减少频繁新建线程和销毁线程带来的性能开销和内存碎片等问题,常用于网络通信和文件读写等任务中。常见的线程池有CachedThreadPool,FixedThreadPool,ScheduledThreadPool,SingleThreadPool这几种。

CachedThreadPool,容量无限,可以缓存。

FixedThreadPool,固定容量,任务量超过最大值时等待。

ScheduledThreadPool,定时延迟执行任务。

SingleThreadPool,单个线程执行,所有任务依次执行。

使用样例如下:

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.fxb.threadtest;
 
import android.util.Log;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 
public class ThreadPoolTest {
 
    public static void cachePoolTest(){
        final ExecutorService cachePool = Executors.newCachedThreadPool();
        for(int i=0; i<10; ++i){
            final int index = i;
            cachePool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        Log.i(MainActivity.TAG, "index is:"+index);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
 
    public static void fixedPoolTest(){
        final ExecutorService fixedPool = Executors.newFixedThreadPool(3);
        for(int i=0; i<10; ++i){
            final int index = i;
            fixedPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        Log.i(MainActivity.TAG, "index is:"+index);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
 
    public static void scheduledPoolTest(){
        final ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(5);
        scheduledPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                Log.i(MainActivity.TAG, "run schedule!");
            }
        }, 1, 3, TimeUnit.SECONDS);
    }
 
    public static void singlePoolTest(){
        final ExecutorService singlePool = Executors.newSingleThreadExecutor();
        for(int i=0; i<10; ++i){
            final int index = i;
            singlePool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        Log.i(MainActivity.TAG, "index is:"+index);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
 
}

测试结果:

CachedPool,0-9瞬间一起打印

FixedPool,0-2,3-5,6-8,9每隔1s打印1组

ScheduledPool,延迟1s,每隔3s打印1次

SinglePool,单个线程执行,0-9每隔1s依次打印。

posted @   丛林小阁楼  阅读(190)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示