• Java线程和线程池


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

    A. 直接new Thread简单方便.

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

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

    其适用的方式如下:

    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,单个线程执行,所有任务依次执行。

    使用样例如下:

    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依次打印。

  • 相关阅读:
    机器语言与汇编语言的关系
    环境变量
    .NET程序运行过程
    【转】计算机组成原理
    将大型 Page Blob 的页范围进行分段
    价格更低、SLA 更强的全新 Azure SQL 数据库服务等级将于 9 月正式发布
    把二元查找树转换成排序的双向链表
    初识C++
    Linux企业级项目实践之网络爬虫(25)——管理源代码之SVN
    Linux企业级项目实践之网络爬虫(24)——定制规则扩展为垂直爬虫
  • 原文地址:https://www.cnblogs.com/MiniHouse/p/6736007.html
Copyright © 2020-2023  润新知