HarmonyOS 多线程

1.异步

2.同步

3.任务组

 

一  异步

 /**
     * 异步
     */
    private void click1() {
        HiLog.info(hiLogLabel, "click1:start");
        TaskDispatcher dispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        dispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "click1:doing1");
            }
        });

        dispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                HiLog.info(hiLogLabel, "click1:doing2");
            }
        });

        dispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "click1:doing3");
            }
        });

    }

 

二  同步

/**
     * 同步
     */
    private void click2() {
        HiLog.info(hiLogLabel, "click2:start");
        TaskDispatcher dispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        dispatcher.syncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "click2:doing1");
            }
        });
        HiLog.info(hiLogLabel, "click2:end1");
        dispatcher.syncDispatch(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                HiLog.info(hiLogLabel, "click2:doing2");
            }
        });
        HiLog.info(hiLogLabel, "click2:end2");
        dispatcher.syncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "click2:doing3");
            }
        });
        HiLog.info(hiLogLabel, "click2:end3");
    }

 

三  任务组

/**
* 任务组
*/
private void click3() {
HiLog.info(hiLogLabel, "click3:start----");
TaskDispatcher dispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
Group group = dispatcher.createDispatchGroup();
dispatcher.asyncGroupDispatch(group, new Runnable() {
@Override
public void run() {
HiLog.info(hiLogLabel, "click3:doing1");
}
});

dispatcher.asyncGroupDispatch(group, new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
HiLog.info(hiLogLabel, "click3:doing2");
}
});

dispatcher.asyncGroupDispatch(group, new Runnable() {
@Override
public void run() {
HiLog.info(hiLogLabel, "click3:doing3");
}
});

//前面3个执行完了,才会执行
dispatcher.groupDispatchNotify(group, new Runnable() {
@Override
public void run() {
HiLog.info(hiLogLabel, "click3:doing4-groupDispatchNotify");
}
});
HiLog.info(hiLogLabel, "click3:start----end");
}
上一篇:创建线程的方法


下一篇:java并发(一):创建线程、线程状态、线程属性