Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
778 views
in Technique[技术] by (71.8m points)

multithreading - android kill specific thread on action bar event

I want to kill an specific thread but can't figure out a way of make it work. I include all info next, even if it does not seem important:

I use action bar sherlock and want to kill a thread on an action button event. So, i have:

    Thread myThread;
    myThread = new Thread(new Runnable(){
        public void run(){
                functionX();
        }
      });
    myThread.start();

This thread is a long running thread, and funcionX() creates some new threads as well. I want to kill the thread when:

   public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()) {

    case android.R.id.home:
        myThread.interrupt();
        break;
    };

I've tried with ExecutorService, using submit(runnable) for a Future result and Future.cancel but does not seems to work. I should also mention that functionX() uses http get requests to get data from a JSON service.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

there are multiple ways you can do this,couple of them can be like

  1. Instead of Thread use TimerTask and call timeTask.cancel() - for interrupting
  2. In the run() method of the thread, keep checking a boolean value to determine whether the thread should be terminated and then you can call interrupt or better throw an Exception

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...