Recently, I have encountered a problem that the thread cannot be stopped. It took a short time to solve this problem. Finally, I can refer to other people's documents to solve it. The following is a summary:
1. The most common method is to control through a Boolean variable.
For example:
class TestThread implements Runnable{boolean flag=true;@Overridepublic void run() {while(flag){doSomething();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}void doSomething(){}}
But when the program starts again, this thread will continue because the thread is not in the run status and the thread has not actually stopped. Therefore, this method is not good.
When the thread sleep () or wait (), call the interrupt () method to cause interruptedexception to exit the thread.
2. If the program stops due to I/O and enters the not runnable state, the interrupt () method cannot be used to cause interruptedexception to exit the thread. How can this exception be caused, depends on the I/O you are using,
For example, if you use Readline () to wait for a message on the network, the thread enters not
Runnable until you read a message, the method you want to leave run () is to close its stream by using close,
In this case, an ioexception is thrown, causing the thread to exit the run () method.
3. If the data is received by the network, you need to disable the socket so that the thread leaves the run () method.
For example:
private DatagramSocket ds=null;private class UDPThread implements Runnable{byte[] buf=new byte[1024];@Overridepublic void run() {while(ds!=null){DatagramPacket dp=new DatagramPacket(buf, buf.length);try {ds.receive(dp);parse(dp);Log.e("tag", "receive a package from server");} catch (IOException e) {e.printStackTrace();}}}
In the preceding example, the DS. Close () method thread must be executed before it can be stopped. Otherwise, the thread will always exist.
4. When the thread is stopped, you can also call the join () method to block the thread. It can be applied to the above situations. Let's introduce it first. If you have any questions, leave a message.