zoukankan      html  css  js  c++  java
  • 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依次打印。

  • 相关阅读:
    python学习第四天 --字符编码 与格式化及其字符串切片
    Lambda表达式 之 C#
    python学习第三天 --布尔类型
    深入理解正则表达式
    《你不知道的JavaScript》第一部分:作用域和闭包
    jquery的extend和fn.extend
    HttpModule与HttpHandler详解
    jQuery分析(2)
    jQuery分析(1)
    jQuery源码中的“new jQuery.fn.init()”什么意思?
  • 原文地址:https://www.cnblogs.com/MiniHouse/p/6736007.html
Copyright © 2011-2022 走看看