java 线程的停止

 1 class MyThread implements Runnable{
2 private boolean flag=true;
3 public void run(){
4 int i=0;
5 while(this.flag){
6 while(true){
7 System.out.println(Thread.currentThread().getName()+"运行,i="+(i++));
8 }
9 }
10 }
11 public void stop(){
12 this.flag=false;
13 }
14 }
15 public class StopDemo {
16 public static void main(String[] args) {
17 MyThread my=new MyThread();
18 Thread t=new Thread(my,"线程");
19 t.start();
20 my.stop();
21 }
22
23 }


 其实停止的方法就是将MyThread类中的flag变量设为false,这样run方法就会停止运行。。。

原文地址:https://www.cnblogs.com/dennisac/p/2394425.html