我希望我的主UI线程在向工作线程发送空消息以执行某些操作之前有效地“休眠”1秒钟。
Sleep()
对我来说是一个问题,因为我在执行quit()
时无法正确sleep()
线程,因此我想将其更改为postDelayed(runnable r, long msDelay)
但需要{ {1}}对象,而不是runnable
。我该如何更改此代码?我只是将空消息从主UI线程传递给工作线程。
UI线程:
Message
和工作线程
public class MainActivity extends Activity
{
static Worker w1, w2;
static Handler mainUIHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
String sender = msg.getData().getString("SENDER");
if (Objects.equals(sender, "CPU1"))
{
mInfoTextView.setText("worker 1 thinking...");
//how to change the following 2 lines to postDelayed()?
try{
Thread.sleep(1000);
} catch (Exception ignored) { }
w2.handler.sendMessage(w2.handler.obtainMessage());
}
}
};
...
}
我尝试创建一个新的Runnable()并将其传递给postDelayed():
class Worker extends HandlerThread
{
...
Worker(String name)
{
super(name);
}
Handler handler= new Handler()
{
@Override
public void handleMessage(Message msg)
{
//perform work
Foo work = dowork();
//communicate work to the UI thread to update the display
Message message = MainActivity.mainUIHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("NAME", name);
bundle.putInt("work", work);
message.setData(bundle);
MainActivity.mainUIHandler.sendMessage(message);
}
};
@Override
public void run()
{
this.setName(WorkerThread.class.getName());
this.setPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
}
}
但它没有触发w2
中的处理程序答案 0 :(得分:1)
您可以使用Handler.sendMessageDelayed()
延迟Message
:
public class MainActivity extends Activity {
// ...
static Handler mainUIHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// ...
w2.handler.sendMessageDelayed(w2.handler.obtainMessage(), 1000);
}
}
}