鸿蒙开发- 线程(一)

<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright (c) 2021 Huawei Device Co., Ltd.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 -->
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="horizontal_center"
    ohos:orientation="vertical"
    ohos:padding="5vp">

    <Button
        ohos:id="$+id:sync_dispatch_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:sync_dispatch"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="50vp"/>

    <Button
        ohos:id="$+id:async_dispatch_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:async_dispatch"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="10vp"/>

    <Button
        ohos:id="$+id:delay_dispatch_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:delay_dispatch"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="10vp"/>

    <Button
        ohos:id="$+id:group_dispatch_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:dispatch_group"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="10vp"/>

    <Button
        ohos:id="$+id:revoke_task_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:revoke_task"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="10vp"/>

    <Button
        ohos:id="$+id:sync_barrier_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:sync_dispatch_barrier"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="10vp"/>

    <Button
        ohos:id="$+id:async_barrier_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:async_dispatch_barrier"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="10vp"/>

    <Button
        ohos:id="$+id:apply_dispatch_button"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="$graphic:button_bg"
        ohos:padding="5vp"
        ohos:text="$string:apply_Dispatch"
        ohos:text_alignment="center"
        ohos:text_size="18fp"
        ohos:top_margin="10vp"/>

    <Text
        ohos:id="$+id:result_text"
        ohos:height="150vp"
        ohos:width="match_parent"
        ohos:background_element="$graphic:common_bg"
        ohos:margin="20vp"
        ohos:multiple_lines="true"
        ohos:padding="10vp"
        ohos:text_size="16fp"/>
</DirectionalLayout>

private void initComponents() {
        Component syncDispatchButton = findComponentById(ResourceTable.Id_sync_dispatch_button);
        Component asyncDispatchButton = findComponentById(ResourceTable.Id_async_dispatch_button);
        Component delayDispatchButton = findComponentById(ResourceTable.Id_delay_dispatch_button);
        Component groupDispatchButton = findComponentById(ResourceTable.Id_group_dispatch_button);
        syncDispatchButton.setClickedListener(this::syncTask);
        asyncDispatchButton.setClickedListener(this::asyncTask);
        delayDispatchButton.setClickedListener(this::delayTask);
        groupDispatchButton.setClickedListener(this::groupTask);
        resultText = (Text) findComponentById(ResourceTable.Id_result_text);
        Component revokeTaskButton = findComponentById(ResourceTable.Id_revoke_task_button);
        Component syncBarrierButton = findComponentById(ResourceTable.Id_sync_barrier_button);
        Component asyncBarrierButton = findComponentById(ResourceTable.Id_async_barrier_button);
        Component applyDispatchButton = findComponentById(ResourceTable.Id_apply_dispatch_button);
        revokeTaskButton.setClickedListener(this::postTaskAndRevoke);
        syncBarrierButton.setClickedListener(this::syncBarrier);
        asyncBarrierButton.setClickedListener(this::asyncBarrier);
        applyDispatchButton.setClickedListener(this::applyDispatchTask);
    }

private void syncTask(Component component) {
        StringBuffer stringBuffer = new StringBuffer();
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.syncDispatch(() -> stringBuffer.append("Sync task1 run").append(System.lineSeparator())
        );
        stringBuffer.append("After sync task1").append(System.lineSeparator());
        globalTaskDispatcher.syncDispatch(() -> stringBuffer.append("Sync task2 run").append(System.lineSeparator()));
        stringBuffer.append("After sync task2").append(System.lineSeparator());
        resultText.setText(stringBuffer.toString());
    }

    private void asyncTask(Component component) {
        StringBuffer stringBuffer = new StringBuffer();
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                HiLog.error(LABEL_LOG, "%{public}s", "AsyncDispatch InterruptedException");
            }
            stringBuffer.append("Async task1 run").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        });
        stringBuffer.append("After async task1").append(System.lineSeparator());
        globalTaskDispatcher.asyncDispatch(() -> {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                HiLog.error(LABEL_LOG, "%{public}s", "AsyncDispatch InterruptedException");
            }
            stringBuffer.append("Async task2 run").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        });
        stringBuffer.append("After async task2").append(System.lineSeparator());
        resultText.setText(stringBuffer.toString());
    }

    private void delayTask(Component component) {
        StringBuffer stringBuffer = new StringBuffer();
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        final long callTime = System.currentTimeMillis();
        globalTaskDispatcher.delayDispatch(() -> {
            stringBuffer.append("DelayDispatch task1 run").append(System.lineSeparator());
            final long actualDelayMs = System.currentTimeMillis() - callTime;
            stringBuffer.append("ActualDelayTime >= delayTime : ").append((actualDelayMs >= DELAY_TIME));
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        }, DELAY_TIME);
        stringBuffer.append("After delayDispatch task1").append(System.lineSeparator());
        resultText.setText(stringBuffer.toString());
    }

    private void groupTask(Component component) {
        StringBuffer stringBuffer = new StringBuffer();
        TaskDispatcher dispatcher = createParallelTaskDispatcher("", TaskPriority.DEFAULT);
        Group group = dispatcher.createDispatchGroup();
        dispatcher.asyncGroupDispatch(group, () -> {
            stringBuffer.append("GroupTask1 is running").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        });
        dispatcher.asyncGroupDispatch(group, () -> {
            stringBuffer.append("GroupTask2 is running").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        });
        dispatcher.groupDispatchNotify(group, () -> stringBuffer.append(
            "This task running after all tasks in the group are completed").append(System.lineSeparator()));
        resultText.setText(stringBuffer.toString());
    }

    private void postTaskAndRevoke(Component component) {
        StringBuffer stringBuffer = new StringBuffer();
        TaskDispatcher dispatcher = getUITaskDispatcher();
        Revocable revocable = dispatcher.delayDispatch(() -> {
            stringBuffer.append("Delay dispatch").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        }, 50);
        boolean revoked = revocable.revoke();
        stringBuffer.append("Revoke result :").append(revoked);
        resultText.setText(stringBuffer.toString());
    }

    private void syncBarrier(Component component) {
        StringBuffer stringBuffer = new StringBuffer();
        TaskDispatcher dispatcher = createParallelTaskDispatcher("SyncBarrierDispatcher", TaskPriority.DEFAULT);
        Group group = dispatcher.createDispatchGroup();
        dispatcher.asyncGroupDispatch(group, () -> stringBuffer.append("Task1 is running").append(System.lineSeparator()));
        dispatcher.asyncGroupDispatch(group, () -> stringBuffer.append("Task2 is running").append(System.lineSeparator()));
        dispatcher.syncDispatchBarrier(() -> stringBuffer.append("Barrier").append(System.lineSeparator()));
        stringBuffer.append("After syncDispatchBarrier").append(System.lineSeparator());
        resultText.setText(stringBuffer.toString());
    }

    private void asyncBarrier(Component component) {
        StringBuffer stringBuffer = new StringBuffer();
        TaskDispatcher dispatcher = createParallelTaskDispatcher("AsyncBarrierDispatcher", TaskPriority.DEFAULT);
        Group group = dispatcher.createDispatchGroup();
        dispatcher.asyncGroupDispatch(group, () -> {
            stringBuffer.append("Task1 is running").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        });
        dispatcher.asyncGroupDispatch(group, () -> {
            stringBuffer.append("Task2 is running").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        });
        dispatcher.asyncDispatchBarrier(() -> {
            stringBuffer.append("Barrier").append(System.lineSeparator());
            handler.postSyncTask(() -> resultText.setText(stringBuffer.toString()));
        });
        stringBuffer.append("After asyncDispatchBarrier").append(System.lineSeparator());
        resultText.setText(stringBuffer.toString());
    }

    private void applyDispatchTask(Component component) {
        StringBuilder stringBuilder = new StringBuilder();
        final CountDownLatch latch = new CountDownLatch(TASK_TOTAL);
        final ArrayList<Long> indexList = new ArrayList<>(TASK_TOTAL);
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.applyDispatch(index -> {
            indexList.add(index);
            latch.countDown();
        }, TASK_TOTAL);
        try {
            latch.await();
        } catch (InterruptedException exception) {
            HiLog.error(LABEL_LOG, "%{public}s", "applyDispatchTask InterruptedException");
        }
        stringBuilder.append("List size matches :").append((indexList.size() == TASK_TOTAL));
        resultText.setText(stringBuilder.toString());
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值