gpt4 book ai didi

java - 如何正确终止/清除/停止/取消从另一个线程启动的线程?

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

我的一个线程正在创建另一个线程以在特定时间间隔内执行某些操作。它是通过计时器来实现的。

现在,当原始线程停止时,另一个线程仍在运行,我无法使其停止。

如何正确终止“线程”?:

Thread thread = new Thread() {

@Override
public void run() {
try {
while (true) {
sleep(1000);
// do something
}
} catch (InterruptedException e) {
Log.e(TAG,"new invoked caught the exception!");
return;
}
}
};

public void run() {
while (true) {
try {
Log.d(TAG,"ConnectedThread.run: Reading from InStream socket");
while (true) {
thread.start();
Log.e(TAG,"starting additional thread");
// Read from the InputStream
int inB;
inB = mmInStream.read();
if (inB != -1) mAccessoryInfo.addCharacter((byte) inB);
}
} catch (IOException e) {
Log.e(TAG, "TADA InStream read exception, disconnected "
+ e.getMessage());
// stopService(new Intent(getBaseContext(), Pinger.class));
thread = null;
connectionLost();
break;
}
}
}

最佳答案

Hi thread is stop by kill() or stop() or destroy method of thread but this all are              
deprecated so dont kill the thread thread is automatically destroy after done its work.
so
if you want to do any work use handler like this not thread in therad.
new Thread() {

public void run() {

try {
Message msg = new Message();
msg.arg2 = 0;
handle.sendMessage(msg);
Thread.sleep(5000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}

//

}

}.start();
and make handler in ur activity like this
public static Handler handle = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.arg2 == 0) {
Toast.makeText(context, "No data to sync.",
Toast.LENGTH_SHORT)
.show();
} else if (msg.arg2 == 1) {
Toast.makeText(context, "Data Sync Completed.",
Toast.LENGTH_SHORT).show();

} else {
Toast.makeText(context, "Data Sync not Completed.",
Toast.LENGTH_SHORT).show();
}

}
};

关于java - 如何正确终止/清除/停止/取消从另一个线程启动的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15239217/

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