从Android中的Activity停止一个帖子

问题描述 投票:0回答:1

我在Android中有下一个Thread来接收数据:

@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();
    }
});

我该怎么做 ?

java android java-threads
1个回答
0
投票

看看你可以用Thread做什么,你会发现它有一个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块中更新它,您的线程自然会到达执行结束。

© www.soinside.com 2019 - 2024. All rights reserved.