gpt4 book ai didi

java - Android Fragment中如何中断线程?

转载 作者:行者123 更新时间:2023-12-01 12:24:07 25 4
gpt4 key购买 nike

我试图中断 Thread ,但它没有中断项。代码如下:

    public class DeviceDetailFragment extends Fragment {

public static CommunicationThread comThread;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
comThread = new CommunicationThread();
new Thread(comThread).start();
}

public static final class CommunicationThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub

while (!Thread.currentThread().isInterrupted()) {
Log.e("TEST", "Thread doing ");
}
Log.e("TEST", "Thread end ");
}
}

@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();

//stop the thread
}
}

我想在onPause中中断线程。但它没有comThread.interrupted

如何中断Android Fragment中的线程?

提前致谢。

最佳答案

使用 boolean 变量可能更容易设置,该变量可以设置为调用者并由线程检查。

    comThread = new CommunicationThread();
new Thread(comThread).start();

Thread.sleep(5000);
comThread.stopThread = true;


public static final class CommunicationThread implements Runnable {
public boolean stopThread = false;

while (!stopThread) {

关于java - Android Fragment中如何中断线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26479714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com