DispatchQueue of Telegram Open Source Project

Introduction to DispatchQueue

Queue of tasks executed serially under a specific thread (single thread)

DispatchQueue role

Serially execute time-consuming or network-related tasks in a specific thread,
such as database operations, Android's sqlite database does not support concurrent operations, and it is not easy to execute in the main thread, so the operations on the database are executed serially in the thread. is safe and does not block the main thread.

DispatchQueue code

public class DispatchQueue extends Thread {

    private volatile Handler handler = null;

    //作用:创建指定线程下的Handler并创建指定的消息队列好和消息循环之前保证添加的任务等待到创建成功后再添加。
    private CountDownLatch syncLatch = new CountDownLatch(1);

    /**
     *
     * @param threadName 任务队列所在的线程名
     */
    public DispatchQueue(final String threadName) {
        setName(threadName);
        start();
    }


    private void sendMessage(Message msg, int delay) {
        try {
            syncLatch.await();
            if (delay <= 0) {
                handler.sendMessage(msg);
            } else {
                handler.sendMessageDelayed(msg, delay);
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }

    /**
     * 取消任务
     * @param runnable
     */
    public void cancelRunnable(Runnable runnable) {
        try {
            syncLatch.await();
            handler.removeCallbacks(runnable);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }

    /**
     * 立刻添加顺序执行的任务
     * @param runnable
     */
    public void postRunnable(Runnable runnable) {
        postRunnable(runnable, 0);
    }

    /**
     * 延时添加顺序执行的任务
     * @param runnable
     */
    public void postRunnable(Runnable runnable, long delay) {
        try {
            syncLatch.await();
            if (delay <= 0) {
                handler.post(runnable);
            } else {
                handler.postDelayed(runnable, delay);
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }

    /**
     * 清空任务队列
     */
    public void cleanupQueue() {
        try {
            syncLatch.await();
            handler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }

    @Override
    public void run() {
        Looper.prepare();
        handler = new Handler();
        syncLatch.countDown();
        Looper.loop();//做的操作是个死循环,线程才不会结束。
    }
}

DispatchQueue code analysis

Handler in Android is a component for distributing messages and tasks, and works in a single thread, so tasks are executed serially.

The Handler created in the thread will not automatically create a message queue and perform message loop operations, so you need to manually create a message queue and perform message loop operations.

Since the creation of Handler is performed in the thread, it is necessary to synchronize the task of adding tasks to the queue and creating the Handler to ensure that the thread of adding tasks is created after the Handler thread, so use CountDownLatch (count reduction lock) to synchronize the threads.

DispatchQueue usage demo

public class TestActivity extends Activity {
    public static class DemoTask implements Runnable{
        int index;

        public DemoTask(int index){
            this.index = index;
        }
        @Override
        public void run() {
            String tag = Thread.currentThread().getName();
            Log.e(tag," 第 "+index+"任务开始");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.e(tag," 第 "+index+"任务完成");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DispatchQueue dispatchQueue = new DispatchQueue("任务队列线程");
        for (int i = 0; i < 10; i++) {
            DemoTask demoTask = new DemoTask(i);
            dispatchQueue.postRunnable(demoTask);
        }
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325504424&siteId=291194637