Java 如何停止或退出“Runnable”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16189254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop or exit "Runnable"
提问by Raj23
I'm new to android.I'm building app to listen incoming message over WiFi , it works fine for listening and updating UI but when i try to exit it doesn't respond to back button press until it receive message in buffer. From my understanding, buttons are on UI thread and Runnable is a separate thread and that's why it doesn't respond to button press immediately coz its busy on separate thread. So how can i interrupt "Runnable" from back button press?
我是 android 新手。我正在构建应用程序来通过 WiFi 收听传入的消息,它可以很好地收听和更新 UI,但是当我尝试退出时,它不会响应后退按钮,直到它在缓冲区中收到消息。根据我的理解,按钮在 UI 线程上,而 Runnable 是一个单独的线程,这就是为什么它不会立即响应按钮按下,因为它在单独的线程上忙碌。那么如何通过按下后退按钮来中断“Runnable”?
Any help would be much appreciated.
任何帮助将非常感激。
public Runnable mUpdate = new Runnable() {
public void run() {
try {
line = in.readLine();
newtext.setText(line);
mHandler.post(this);
Log.i("RESPONSE FROM SERVER", "S: Received Message: '" +line+ "'");
//onBackPressed();
//threadRunning = true;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error" , "Something Happen");
}
}
};
Edit : Sorry, I should have post this earlier , so in "onCreate" , i use handler to call "mUpdate" . Is it the right way to call or not?
编辑:对不起,我应该早点发布这个,所以在“onCreate”中,我使用处理程序来调用“mUpdate”。打电话或不打电话的方式正确吗?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
setContentView(R.layout.activity_display_message);
message = intent.getStringArrayExtra(MainActivity.EXTRA_MESSAGE);
newtext = (TextView)findViewById(R.id.TextView1);
userName = message[0];
serverIP = message[1];
sendConnectionRequest ();
mHandler = new Handler(); // Handler to update UI
mHandler.post(mUpdate); // post is a method to update UI
}
采纳答案by Philip Couling
Edit:
编辑:
Now that you've added code that involves the Handlerit's now clearer where your trouble lies. Some points to understand:
既然您已经添加了涉及Handler 的代码,那么您的问题所在就更清楚了。需要理解的几点:
- Android has a general concept that there is themain thread and then there are many other threads.
- Only the main thread may modify the UI
- In later versions of android the main thread is not allowed to do networking...
- Android有一个总的概念,有在主线程,然后还有很多其他的线程。
- 只有主线程可以修改 UI
- 在更高版本的android中,主线程不允许进行网络...
So how to change the UI based on reading something from the network?
那么如何根据从网络中读取的内容来更改 UI?
You need to pass a message from another (networking) thread to the main thread. The Handler let's your other thread give a message to the main thread... That is your networking thread can give a task (Runnable
) to the main thread to perform. The handler posts the task from the networking thread to the main thread.
您需要将消息从另一个(网络)线程传递到主线程。处理程序让你的另一个线程给主线程一个消息......那是你的网络线程可以给Runnable
主线程执行一个任务()。处理程序将任务从网络线程发布到主线程。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
setContentView(R.layout.activity_display_message);
message = intent.getStringArrayExtra(MainActivity.EXTRA_MESSAGE);
newtext = (TextView)findViewById(R.id.TextView1);
userName = message[0];
serverIP = message[1];
sendConnectionRequest ();
mHandler = new Handler(); // Handler to update UI
// This is being created in the main thread
// so everything posted will be posted to
// the main thread
mUpdate.start(); // start thread to do something on the network
//before updating the UI
}
public Thread mUpdate = new Thread() {
public void run() {
try {
while (!thread.interrupted()) {
final String line = in.readLine();
Log.i("RESPONSE FROM SERVER", "S: Received Message: '" +line+ "'");
// Define the UI change you want to make
Runnable uiUpdate = new Runnable() {
public void run() {
// modify your UI here.
newtext.setText(line);
}
};
// post the UI change back to the main thread.
mHandler.post(uiUpdate);
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error" , "Something Happen");
}
}
public void interrupt() {
try {
super.interrupt();
in.close();
}
catch (IOException e) {}
}
};
May I suggest you also:
我也可以建议你:
protected void onDestroy() {
mUpdate.interrupt();
}
Original Answer (Now defunct)
原始答案(现已失效)
From my understanding, buttons are on UI thread and Runnable is a separate thread and that's why it doesn't respond to button press immediately coz its busy on separate thread.
根据我的理解,按钮在 UI 线程上,而 Runnable 是一个单独的线程,这就是为什么它不会立即响应按钮按下,因为它在单独的线程上忙碌。
That's not correct at all.
A Threadis a separate thread not a Runnable. And you need to call start()
not run()
on the thread to make the run method execute in its own thread. The whole point of using threads is that one thread will not (usually) be blocked by another being busy.
这根本不正确。一个线程是一个单独的线程不是一个Runnable。并且您需要在线程上调用start()
notrun()
以使 run 方法在其自己的线程中执行。使用线程的全部意义在于一个线程不会(通常)被另一个线程阻塞。
// <snip>removed for brevity of new answer</snip>
You can also look into an AsyncTaskfrom the android library. This will also run in its own thread if you use it correctly.
您还可以查看android 库中的AsyncTask。如果您正确使用它,这也将在其自己的线程中运行。
回答by Eugene
I have no idea how that relates to Android, but judging from your title, stopping a thread in Java is done with interrupts, which are handled by the OS itself.
我不知道这与 Android 有什么关系,但从你的标题来看,在 Java 中停止线程是通过中断完成的,这些中断由操作系统本身处理。
From you Thread you interrupt the other one.
从你 Thread 你打断另一个。
theOtherThread.interrupt() //--> inside your Thread.
And on the other side:
另一方面:
public void run(){
while(true){
try{
//handle your logic
Thread.sleep(100);
}catch(InterruptedException){
//thread was 'stopped' here
Thread.currentThread().interrupt(); //this is a MUST
break;
}
}
}