how to use thread

本文探讨了在程序中使用线程显示工作进度时遇到的同步问题。原本期望线程能够与主程序并行运行,但实际上线程仅短暂运行便被主程序抢占资源。为解决该问题,作者将工作负载拆分为独立线程,实现了真正的并行执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Just got a problem which wasted me some time. The problem is just:

 

Regarding a procedure A, which mainly implements a work B, I want to use a progress bar to show the progress of the work of B, because A need to run a lot of sub functions and take a lot of time. So inside A, right before executing the code directly related to B's work, I insert a few code to create a thread C to display the progress of B, and after the code of creating the thread C, I continue to put A's original code.

 

I thought C will work with A's code at the same time(sychronization), since it is thread. However the result is, although thread C starts to work, but just for one second, then A's code takes over CPU until A gets finished, and then B continues. This makes using thread C no sense.

 

Then I found the reason: because thread C is created inside the code of A, then CPU have more priority for A. It always tries to finish more work of  A.

 

Solution:

I put the code in A related to work B out and make it a separate thread D to do the work. Then in procedure A, I create the thread C at first, and then create thread D (which does the work B). Now these two threads have the same prority, and then their run are sychoronized.

在Android开发中,线程(Thread)、Looper和Handler是处理异步操作的关键组件。以下是如何使用它们的一个简单示例: 1. **创建新线程**(Thread): ```java // 创建一个新的线程 Thread myThread = new Thread(new Runnable() { @Override public void run() { // 这里写你的线程任务,如网络请求或耗时计算 System.out.println("Running in background thread"); } }); // 启动线程 myThread.start(); ``` 2. **Looper与Handler**通常用于消息传递和事件循环,尤其是在UI线程(主线程)中,因为UI更新必须在主线程上执行。创建Handler: ```java Handler mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { // 处理接收到的消息 super.handleMessage(msg); Log.d("Handler", "Handling message: " + msg.what); } }; ``` 在子线程中发送消息到主线程: ```java // 在子线程中 mHandler.sendMessage(Message.obtain(mHandler, 1)); // 假设msg.what=1是一个标识符 ``` 3. **Runnable接口**: 如果你想在一个线程中执行一些任务,但不关心它是否在主线程中运行,可以使用Runnable接口: ```java Thread workerThread = new Thread(new Runnable() { @Override public void run() { // 执行任务 doSomethingExpensive(); } private void doSomethingExpensive() { // ... } }); workerThread.start(); ``` 相关问题: 1. 如何避免在Android UI线程中执行耗时操作? 2. Handler和其他线程通信机制的区别是什么? 3. Android中何时会自动创建Looper?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值