[英]UI Thread gets stuck even though I'm working on another
I have this code that on a click of a button a service will be started from a new thread and the service will start my TCP Client. 我有这段代码,单击按钮后,将从新线程启动服务,该服务将启动我的TCP客户端。
The TCP client, once connected will send a count down event to inform the fragment to continue working. 一旦连接,TCP客户端将发送一个倒计时事件,以通知该片段继续工作。
the code looks like this 代码看起来像这样
connectButton = (Button) view.findViewById(R.id.connectBT);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// ***** IntentService Way ****** //
Intent intent = new Intent(getActivity(), NetworkService.class);
getActivity().startService(intent);
// Once client is connected, give the server some info about client
mCountDown.await(3000, TimeUnit.MILLISECONDS);
String json = jsonMaker.toJson(new DeviceInfo());
DispatchToServer(json);
} catch (Exception ie) {
ie.getMessage();
}
}
}).run();
but when I click connect, my UI still freezes for some reason, even though I'm waiting on a different thread then the UI thread. 但是当我单击connect时,即使我在等待与UI线程不同的线程,UI仍然由于某些原因冻结。 Same code worked fine when I used an AsyncTask instead of the service. 当我使用AsyncTask代替服务时,相同的代码工作正常。
You have written 你写
new Thread(new Runnable() {...}).run();
Thread#run
is just the Thread
class's implementation of the Runnable
interface. Thread#run
只是Runnable
接口的Thread
类的实现。 All it does is delegate to the run
method of the Runnable
you have passed to the constructor. 它所做的只是委托给您传递给构造函数的Runnable
的run
方法。
Java threads are started with the start
method: Java线程使用start
方法start
:
new Thread(new Runnable() {...}).start();
尝试调用thread.start()而不是thread.run()
使用Thread.start()而不是Thread.run()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.