[Huawei Developers] muraliameakula:
Introduction

When you need to process a time-consuming operation. For example, executing a download task in the current thread without blocking the thread, try out the EventHandler to achieve efficient communications between different threads in HarmonyOS. You can use EventRunner to create another thread to run time-consuming tasks without blocking the current thread. In this way, all types of tasks can run more smoothly and effectively in different threads. For example, you can use EventHandler in the main thread to create a child thread to download an image. The EventHandler will notify the main thread when the image is downloaded in child thread, and the main thread can update the UI display.

Limitations and Constraints

During inter-thread communication, the EventHandler can be bound only to the threads created by the EventRunner. When creating an EventRunner instance, ensure that the creation is successful. An EventHandler can be bounded to threads created by an EventRunner instance only when the EventRunner instance is not null.

An EventHandler can be bounded only one EventRunner at a time. However, an EventRunner can be bounded to multiple EventHandler instances at the same time.

When to Use

Development Scenarios of EventHandler

The EventHandler dispatches InnerEvent instances or Runnable tasks to other threads for processing, including the following situations:

An InnerEvent instance needs to be dispatched to a new thread and to be processed based on the priority and delay time. The priority of an InnerEvent can be IMMEDIATE, HIGH, LOW, or IDLE, and the delay time can be specified.

A Runnable task needs to be dispatched to a new thread and to be processed based on the priority and delay time. The priority of a Runnable task can be IMMEDIATE, HIGH, LOW, or IDLE, and the delay time can be specified.

An event needs to be dispatched from a new thread to the original thread for processing.

Development Overview

You need to install DevEcho studio IDE and I assume that you have prior knowledge about the Harmony OS and java.

Hardware Requirements

A computer (desktop or laptop) running Windows 10.

A Huawei phone (with the USB cable), which is used for debugging.

Software Requirements

Java JDK installation package.

DevEcho studio installed.

HMS Core (APK) 4.X or later.

Follows the steps.

1. Create Harmony Project.

Open DevEcho studio.

Click NEW Project, select a Project Templet.

Select ability template and click Next as per below image.

Enter Project and Package Name and click on Finish.

2. Once you have created the project, DevEco Studio will automatically sync it with Gradle files. Find the below image after synchronization is successful.

3. Update Permission and app version in config.json file as per your requirement, otherwise retain the default values.

4. Create New Ability as follows.

5. Development Procedure.

Add the below code in MainAbilitySlice.java

package com.hms.interthreadcom.slice;
import com.hms.interthreadcom.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import java.util.stream.IntStream;
public class MainAbilitySlice extends AbilitySlice {
public static final int CODE_DOWNLOAD_FILE1 = 1;
public static final int CODE_DOWNLOAD_FILE2 = 2;
public static final int CODE_DOWNLOAD_FILE3 = 3;
HiLogLabel LABEL_LOG;
Text handlerTV;
Button interThreadBtn,bankingSystemBtn,delayInterThreadBtn;
EventRunner runnerA;
MyEventHandler handler;
MyEventHandler handler2;
Customer customer;
// 1. Create a class that inherits from EventHandler.
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
handlerTV=(Text)findComponentById(ResourceTable.Id_text_helloworld);
interThreadBtn=(Button)findComponentById(ResourceTable.Id_inter_thread);
delayInterThreadBtn=(Button)findComponentById(ResourceTable.Id_delay_inter_thread);
bankingSystemBtn=(Button)findComponentById(ResourceTable.Id_inter_thread_banking_system);
LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
interThreadBtn.setClickedListener(component -> executeTask());
delayInterThreadBtn.setClickedListener(component -> executeTaskWithDelay());
bankingSystemBtn.setClickedListener(component -> interThreadInBankingSystem());
// Thread A:
runnerA = EventRunner.create("downloadRunner");
handler = new MyEventHandler(runnerA);
handler2 = new MyEventHandler(runnerA);
}
private void interThreadInBankingSystem() {
customer=new Customer();
new Thread(() -> customer.withdraw(15000)).start();
new Thread(() -> customer.deposit(10000)).start();
}

private void executeTaskWithDelay() {
handler.sendEvent(CODE_DOWNLOAD_FILE1,2 , EventHandler.Priority.HIGH);
handler.sendEvent(CODE_DOWNLOAD_FILE2);
handler.sendEvent(CODE_DOWNLOAD_FILE3);
}

private void executeTask() {
// 3. Send events to thread A.
handler.sendEvent(CODE_DOWNLOAD_FILE1);
handler.sendEvent(CODE_DOWNLOAD_FILE2);
handler.sendEvent(CODE_DOWNLOAD_FILE3);
}

@Override
public void onActive() {
super.onActive();
}

@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
public class MyEventHandler extends EventHandler {
MyEventHandler(EventRunner runner) {
super(runner);
}
@Override
public void processEvent(InnerEvent event) {
super.processEvent(event);
if (event == null) {
return;
}

int eventId = event.eventId;
switch (eventId) {
case CODE_DOWNLOAD_FILE1: {
handlerTV.setText("Please wait image downloading...");
HiLog.info(LABEL_LOG, "The Image 1 is downloading please wait");
break;
}
case CODE_DOWNLOAD_FILE2: {
IntStream.rangeClosed(0, 100).forEach(i -> HiLog.info(LABEL_LOG, "The Image" + i + "is downloading please wait"));
break;
}
case CODE_DOWNLOAD_FILE3: {
handlerTV.setText("Image downloading successfully");
HiLog.info(LABEL_LOG, "The Image done");
break;
}
default:
break;
}
}
}
public class Customer {
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{
wait();
}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

}

Add the below code in ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Button
ohos:id="$+id:inter_thread"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="$string:mainability_interthread"
ohos:text_size="22fp"
ohos:padding="10vp"
ohos:margin="20vp"
ohos:background_element="$graphic:background_button"></Button>
<Button
ohos:id="$+id:delay_inter_thread"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="$string:mainability_delay_interthread"
ohos:text_size="22fp"
ohos:padding="10vp"
ohos:margin="20vp"
ohos:background_element="$graphic:background_button"></Button>
<Button
ohos:id="$+id:inter_thread_banking_system"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="$string:mainability_banking_system"
ohos:text_size="22fp"
ohos:padding="10vp"
ohos:margin="20vp"
ohos:background_element="$graphic:background_button"></Button>

<Text
ohos:id="$+id:text_helloworld"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_main"
ohos:layout_alignment="horizontal_center"
ohos:text_size="40vp"
/>

</DirectionalLayout>

6. To build apk and run in device, choose Build > Generate Key and CSR Build for Hap(s)\ APP(s) or Build and Run into connected device, follow the steps.

Result

Click on UI Inter Thread Communication button. It will execute an image download time-consuming operation task in the current thread without blocking the thread.

Pros: You can perform time consuming operation without blocking current thread.

Cons: If you trying to execute time consuming operation without

2. Click on‘Banking System’ button, it will communicate between two thread.

Pros: You can communicate between two threads. Only single thread to access the shared resource.

Cons: Increase the waiting time of the thread. Create performance problem.

Tips and Tricks

Always use the latest version of DevEcho Studio.

Use Harmony Device Simulator from HVD section.

Conclusion

In this article, we have learnt Inter Thread Management in Harmony OS. EventHandler mainly used for time-consuming operation task in current thread without blocking the thread, try out the EventHandler to achieve efficient communications between different threads in HarmonyOS.

Thanks for reading the article, please do like and comment your queries or suggestions.

References

Harmony OS: https://www.harmonyos.com/en/develop/

Harmony OS Thread Management:

https://developer.harmonyos.com/en/docs/documentation/doc-guides/inter-thread-guidelines-0000000000038955

Original Source