Android starts a subthread, which is an endless loop and cannot print "Hello ".
Now, how can I click a Button to terminate the subthread?
Stop () does not work. If destroy () has an exception, Handler does not seem to be able to solve it because it is a thread...
The answer is as follows:
Thread is like this: Thread {boolean flag = fase; run () {while (! Flag) {}} Thread t = new Thread (); t. start (); ------------------------------------------------------- to terminate the loop, you only need to t. flag = true; ========================================================== another method of thread is as follows: thread {run () {while (true) {Thread. sleep (xxxx) ;}} Thread t = new Thread (); t. start (); ------------------------------------------ to terminate the loop, you only need to t. interrupte (); but pay attention to the call time here. It should be called within xxxx time after the sub-thread executes the sleep (xxxx) in the run method. That is, the sub-thread will sleep for a while, wake up for a while, and wake up for a while. It will be called when the sub-thread falls asleep.
The thread stops after the Android program exits.
Www.2cto.com
Tested: the following method can terminate a thread.
Method 1: System. exit (0 );
Method 2: android. OS. Process. killProcess (android. OS. Process. myPid () // slightly delayed when disabled
0
A question about thread stop after Android program exits 10
In Android programs, the UI thread is the main thread.
Theoretically, after the Activity calls the finish method, the main thread is terminated.
Then the sub-thread on it should also be stopped
However, the test shows that this is not the case.
After the program exits, the sub-thread is still running in the background.
The thread must be stopped with DDMS.
So how do I stop all enabled Sub-threads when the program exits?
I thought of two solutions:
1. Change the identifier of the loop in the thread upon exit
While (isRun ){...}
Setting isRun to false breaks the loop and ends the thread.
2. Do not use a loop like while (isRun) {...}
The Handler mechanism provided by Android is used to complete
Java code
// Add a thread to the thread queue immediately and execute its [color = red] run [/color] Method
Handler. post (test );
Runnable test = new Runnable (){
Public void run (){
// The above code is omitted
// The latency is 1000 milliseconds. run the [color = red] run [/color] method of this thread.
Handler. postDelayed (test, 1000 );
}
}
// Exit
// Remove the thread from the thread queue and it will not be executed
Handler. removeCallbacks (test );
For example, the red-letter mark is indeed the run method called, so a sub-thread is not actually started.