英文:
How to cancel a specific thread in android studio?
问题
如果在这15秒内按下按钮,我该如何取消这个线程?
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
sound1.setVolume(1, 1);
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
}
}, 15000);
如果我有两个与上面相同的线程,我如何引用其中一个?
英文:
How can I cancel this thread in case a button is pressed under those 15 seconds?
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
sound1.setVolume(1, 1);
} catch (Exception e) {
Log.e("Exception", e.getMessage());
} }
},15000);
What if I have 2 treads each one same like the above? How can I refer to one of them?
答案1
得分: 2
你可以创建自己的线程类,这样你就可以通过它们的名称来访问。
public class Sound extends Thread {
public boolean stop = false;
public void run() {
try {
for (int i = 0; i < 150; i++) {
if (stop) {
return;
}
sleep(100);
System.out.println(i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
然后你可以像这样停止线程:
Sound s = new Sound();
s.start();
.
.
.
s.stop = true;
英文:
You can create your own thread class, so you can access them by their name.
public class Sound extends Thread {
public boolean stop = false;
public void run() {
try {
for (int i = 0; i < 150; i++) {
if (stop) {
return;
}
sleep(100);
System.out.println(i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Then you can stop thread like this;
Sound s = new Sound();
s.start();
.
.
.
s.stop = true;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论