我在Android中拥有下一个线程来接收数据:
@Override
public void run() {
try{
ServerSocket ss=new ServerSocket(puerto);
int contador=0;
while(!end){
try{
ss.setSoTimeout(6000);
Socket s=ss.accept();
BufferedReader input=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output=new PrintWriter(s.getOutputStream());
stringData=input.readLine();
output.flush();
contador++;
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
output.close();
s.close();
}catch (SocketTimeoutException e){
e.printStackTrace();
end=true;
}
}
ss.close();
}catch (IOException e){
e.printStackTrace();
}
}
当代码到达SocketTimeOutException时,我想从下一个活动中停止线程:
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dirIP=editTextDirIP.getText().toString();
hebraRecibir.start();
hebraEnviar.start();
}
});
我该怎么办?
答案 0 :(得分:0)
查看线程可以做什么,您会看到它有一个stop方法。但是,您还将看到它已被弃用。查看有关其弃用的说明可以很清楚地了解到
* @deprecated This method is inherently unsafe. Stopping a thread with
* Thread.stop causes it to unlock all of the monitors that it
* has locked (as a natural consequence of the unchecked
* <code>ThreadDeath</code> exception propagating up the stack). If
* any of the objects previously protected by these monitors were in
* an inconsistent state, the damaged objects become visible to
* other threads, potentially resulting in arbitrary behavior. Many
* uses of <code>stop</code> should be replaced by code that simply
* modifies some variable to indicate that the target thread should
* stop running. The target thread should check this variable
* regularly, and return from its run method in an orderly fashion
* if the variable indicates that it is to stop running. If the
* target thread waits for long periods (on a condition variable,
* for example), the <code>interrupt</code> method should be used to
* interrupt the wait.
* For more information, see
* <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
* are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
因此,您应该像使用以下操作一样在线程内进行检查:end
变量。在finally块中对其进行更新,您的线程自然会到达其执行结束。