如何在Android Studio中取消特定线程?

huangapple go评论70阅读模式
英文:

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 &lt; 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;

huangapple
  • 本文由 发表于 2020年10月14日 05:37:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64343520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定