How to stop a process

https://cloud.tencent.com/developer/article/1451817

  1. Use exit signs, the thread exits normally, that is, after the completion of the thread run method terminates.
  2. Use interrupt method interrupt thread.
  3. Not recommended stop, suspend and resume methods. Equivalent to the computer power off, it is unsafe method.

Use the exit sign

Among thread usually write cycle, write cycle if you do not, things can get a word, there is no need to open a thread to handle. stop out of date and the end of the run method. When turned on multi-threaded, running code is usually cyclic structure, as long as the cycle under control, you can let the end of the run method, which is the end of the thread. How it works: As long as the loop terminates, the thread will cease.

public class StopThread implements Runnable{ private volatile boolean flag = true; @Override public void run() { while (flag) { System.out.println(Thread.currentThread().getName() + "...run"); } System.out.println("...stop"); } public void set() { flag = false; } }

Use a keyword volatile, to ensure the visibility of the current flag in the multi-core CPU.

package com.liukai.thread.stop;

public class MyThread extends Thread { public void run(){ super.run(); try { for(int i=0; i<5000; i++){ if (i == 100) { System.out.println("主动中断线程"); Thread.currentThread().interrupt(); } System.out.println("i="+(i+1)); Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } }

Guess you like

Origin www.cnblogs.com/JMrLi/p/11593571.html