Android性能优化专项Android安卓基础

Android实现具有优先级的线程池

2022-05-27  本文已影响0人  在岁月中远行

在安卓开发中为了复用线程以及节约线程开销,线程池是一种比较多的方法,有时也会有这样的需求,不同的线程执行任务的紧急程度不一样的,加入线程池的任务可能需要优先处理,在ThreadPoolExector的构造函数需要传递一个继承BlockQueue的子类。

在SDK中已经提供一个PriorityBlockQueue这样的优先级阻塞队列,我们要的就是扩展Runnable,添加一个优先级的属性

然后就是为PriorityBlockungQueue的构造函数第二个参数,继承Comparator实现一个比较优先级的类

后面我们写主要代码

exe.execute(new RunWithPriority(31) {

@Override

    public void run() {

Log.d("tanlinstarted",this.getPriority() +" started");

        try {

Thread.sleep(3000);

        }catch (InterruptedException ex) {

}

Log.d("tanlin",this.getPriority() +" finished");

    }

});

exe.execute(new RunWithPriority(45) {

@Override

    public void run() {

Log.d("tanlinstarted",this.getPriority() +" started");

        try {

Thread.sleep(3000);

        }catch (InterruptedException ex) {

}

Log.d("tanlin",this.getPriority() +" finished");

    }

});

exe.execute(new RunWithPriority(77) {

@Override

    public void run() {

Log.d("tanlinstarted",this.getPriority() +" started");

        try {

Thread.sleep(3000);

        }catch (InterruptedException ex) {

}

Log.d("tanlin",this.getPriority() +" finished");

    }

});

exe.execute(new RunWithPriority(7) {

@Override

    public void run() {

Log.d("tanlinstarted",this.getPriority() +" started");

        try {

Thread.sleep(3000);

        }catch (InterruptedException ex) {

}

Log.d("tanlin",this.getPriority() +" finished");

    }

});

exe.execute(new RunWithPriority(1) {

@Override

    public void run() {

Log.d("tanlinstarted",this.getPriority() +" started");

        try {

Thread.sleep(3000);

        }catch (InterruptedException ex) {

}

Log.d("tanlin",this.getPriority() +" finished");

    }

});

可以从日志看出来前面优先级99和10这两个是核心线程

后面的线程加入队列进行排序按照优先级数值越小,越执行早。

首先线程池的调度是,系统Cpu利用时间碎片随机去调度的。我们的设置的只能尽可能的去满足,按照优先级去执行,但不能100%保证。

上一篇下一篇

猜你喜欢

热点阅读