如何正确中断android中的线程

时间:2021-06-06 21:02:51

In my application I have a button and when it gets clicked I start a new thread and change the text of button. If I press the button again it will start changing its text faster.

在我的应用程序中,我有一个按钮,当它被点击时,我开始一个新的线程并更改按钮的文本。如果我再次按下按钮,它将开始更快地更改文本。

I would like to interrupt the thread when the button is pressed in the second time. What's the correct way to do it?

我想在第二次按下按钮时中断线程。这样做的正确方法是什么?

public class TestActivity extends Activity {

 Button btn;
 int i = 0;

 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     btn = (Button)findViewById(R.id.btn);
     btn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           runThread();
       }
     });
 }

private void runThread() {
    new Thread() {
      public void run() {
          while (i++ < 1000) {
              try {
                  runOnUiThread(new Runnable() {

                      @Override
                      public void run() {
                          btn.setText("#" + i);
                      }
                  });
                  Thread.sleep(300);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
    }.start();
}

6 个解决方案

#1


2  

In my opinion, the best way would be using a variable to control this.

在我看来,最好的方法是使用变量来控制它。

Something like:

就像是:

while(i++ < 1000 && keepRunning)

I see that as a good solution because it cant cause unexpected behavior, as you are sure the exactly moment your thread would exit.

我认为这是一个很好的解决方案,因为它无法导致意外行为,因为您确定线程将退出的确切时刻。

extra--

额外 -

As a suggestion, I also would recommend you to set your thread non-Damon (setDaemon(false)) because it makes layout changes

作为一个建议,我也建议你设置你的线程非Damon(setDaemon(false)),因为它使布局更改

Also it is a good practice to give thread a name (setName()) to make it easy on debugging.

同样,给线程一个名称(setName())是一个很好的做法,以便于调试。

#2


2  

In this case, just keep a reference to your thread and use Thread.interrupt():

在这种情况下,只需保留对线程的引用并使用Thread.interrupt():

private Thread runThread() {

return new Thread() {
  public void run() {
      while (i++ < 1000) {
          try {
              runOnUiThread(new Runnable() {

                  @Override
                  public void run() {
                      btn.setText("#" + i);
                  }
              });
              Thread.sleep(300);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
}

Then:

然后:

 btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       if (myThread != null) myThread.interrupt();
       myThread = runThread();
       myThread.start();
   }
 });

Read this post for more info and options:

阅读这篇文章了解更多信息和选项:

How to properly stop the Thread in Java?

如何在Java中正确停止Thread?

#3


1  

Right now you start a new Thread each time you press the button.

现在,每次按下按钮都会启动一个新线程。

Something like this should work.

这样的事情应该有效。

public class TestActivity extends Activity {

Button btn;
int i = 0;
Thread countThread = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countThread = new Thread() {
    public void run() {
      while (i++ < 1000) {
          try {
              runOnUiThread(new Runnable() {

                  @Override
                  public void run() {
                      btn.setText("#" + i);
                  }
              });
              Thread.sleep(300);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
 }
 btn = (Button)findViewById(R.id.btn);
 btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       runThread();
   }
 });
}

private void runThread() {
  if(countThread != null) {
    if(countThread.isAlive()) {
        countThread.stop();
    } else {
        countThread.start();
    }
  }
}

I only had a text editor so I can't guarantee if this solves your problem.

我只有一个文本编辑器,所以我不能保证这是否解决了你的问题。

#4


0  

Try this, Just take another variable j and it will handle your code:-

试试这个,只需要另外一个变量j,它将处理你的代码: -

public class TestActivity extends Activity {

     Button btn;
     int i = 0,j=0;

     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         btn = (Button)findViewById(R.id.btn);
         btn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
                j=1;
               runThread();
           }
         });
     }

    private void runThread() {
        new Thread() {
          public void run() {
              while (i++ < 1000) {
                  try {
                      runOnUiThread(new Runnable() {

                          @Override
                          public void run() {
                              if(j==1){
                              btn.setText("#" + i);
                               j=0;
                               }
                                else
                                    Thread.interrupted();
                          }
                      });
                      Thread.sleep(300);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
        }.start();
    }

#5


0  

You can use normal Thread in Android (and call interrupt() for your use case) but frameworks provides other better options by providing helper classes around Threads. You can refer to official documentation page for other options.

您可以在Android中使用普通的Thread(并为您的用例调用interrupt()),但框架通过提供围绕Threads的帮助程序类提供了其他更好的选项。您可以参考官方文档页面了解其他选项。

HandlerThread is preferred option. You can call quitSafely() or quit() for your use case if you go for HandlerThread

HandlerThread是首选选项。如果你使用HandlerThread,你可以为你的用例调用quitSafely()或quit()

Related post:

相关文章:

Why use HandlerThread in Android

为什么在Android中使用HandlerThread

#6


0  

You can use thread.interrupt() to interrupt the thread.

您可以使用thread.interrupt()来中断线程。

#1


2  

In my opinion, the best way would be using a variable to control this.

在我看来,最好的方法是使用变量来控制它。

Something like:

就像是:

while(i++ < 1000 && keepRunning)

I see that as a good solution because it cant cause unexpected behavior, as you are sure the exactly moment your thread would exit.

我认为这是一个很好的解决方案,因为它无法导致意外行为,因为您确定线程将退出的确切时刻。

extra--

额外 -

As a suggestion, I also would recommend you to set your thread non-Damon (setDaemon(false)) because it makes layout changes

作为一个建议,我也建议你设置你的线程非Damon(setDaemon(false)),因为它使布局更改

Also it is a good practice to give thread a name (setName()) to make it easy on debugging.

同样,给线程一个名称(setName())是一个很好的做法,以便于调试。

#2


2  

In this case, just keep a reference to your thread and use Thread.interrupt():

在这种情况下,只需保留对线程的引用并使用Thread.interrupt():

private Thread runThread() {

return new Thread() {
  public void run() {
      while (i++ < 1000) {
          try {
              runOnUiThread(new Runnable() {

                  @Override
                  public void run() {
                      btn.setText("#" + i);
                  }
              });
              Thread.sleep(300);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
}

Then:

然后:

 btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       if (myThread != null) myThread.interrupt();
       myThread = runThread();
       myThread.start();
   }
 });

Read this post for more info and options:

阅读这篇文章了解更多信息和选项:

How to properly stop the Thread in Java?

如何在Java中正确停止Thread?

#3


1  

Right now you start a new Thread each time you press the button.

现在,每次按下按钮都会启动一个新线程。

Something like this should work.

这样的事情应该有效。

public class TestActivity extends Activity {

Button btn;
int i = 0;
Thread countThread = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countThread = new Thread() {
    public void run() {
      while (i++ < 1000) {
          try {
              runOnUiThread(new Runnable() {

                  @Override
                  public void run() {
                      btn.setText("#" + i);
                  }
              });
              Thread.sleep(300);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
 }
 btn = (Button)findViewById(R.id.btn);
 btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       runThread();
   }
 });
}

private void runThread() {
  if(countThread != null) {
    if(countThread.isAlive()) {
        countThread.stop();
    } else {
        countThread.start();
    }
  }
}

I only had a text editor so I can't guarantee if this solves your problem.

我只有一个文本编辑器,所以我不能保证这是否解决了你的问题。

#4


0  

Try this, Just take another variable j and it will handle your code:-

试试这个,只需要另外一个变量j,它将处理你的代码: -

public class TestActivity extends Activity {

     Button btn;
     int i = 0,j=0;

     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         btn = (Button)findViewById(R.id.btn);
         btn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
                j=1;
               runThread();
           }
         });
     }

    private void runThread() {
        new Thread() {
          public void run() {
              while (i++ < 1000) {
                  try {
                      runOnUiThread(new Runnable() {

                          @Override
                          public void run() {
                              if(j==1){
                              btn.setText("#" + i);
                               j=0;
                               }
                                else
                                    Thread.interrupted();
                          }
                      });
                      Thread.sleep(300);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
        }.start();
    }

#5


0  

You can use normal Thread in Android (and call interrupt() for your use case) but frameworks provides other better options by providing helper classes around Threads. You can refer to official documentation page for other options.

您可以在Android中使用普通的Thread(并为您的用例调用interrupt()),但框架通过提供围绕Threads的帮助程序类提供了其他更好的选项。您可以参考官方文档页面了解其他选项。

HandlerThread is preferred option. You can call quitSafely() or quit() for your use case if you go for HandlerThread

HandlerThread是首选选项。如果你使用HandlerThread,你可以为你的用例调用quitSafely()或quit()

Related post:

相关文章:

Why use HandlerThread in Android

为什么在Android中使用HandlerThread

#6


0  

You can use thread.interrupt() to interrupt the thread.

您可以使用thread.interrupt()来中断线程。