1.7.8使用return 停止线程

 1 package com.cky.thread;
 2 
 3 /**
 4  * Created by edison on 2017/12/3.
 5  */
 6 public class MyThread12 extends Thread{
 7     @Override
 8     public void run() {
 9         super.run();
10             for (int i = 0; i < 50000; i++) {
11                 if (Thread.interrupted()) {
12                     System.out.println("子线程已经停止了,我要退出");
13                     return;
14                 }
15                 System.out.println("i="+(i+1));
16             }
17             System.out.println("for循环后继续执行");
18 
19     }
20 }
 1 package com.cky.test;
 2 
 3 import com.cky.thread.MyThread12;
 4 
 5 /**
 6  * Created by edison on 2017/12/3.
 7  */
 8 public class Test {
 9     public static void main(String[] args) {
10         try {
11             MyThread12 myThread12 = new MyThread12();
12             myThread12.start();
13             Thread.sleep(2);
14             myThread12.interrupt();
15         } catch (InterruptedException e) {
16             e.printStackTrace();
17         }
18     }
19 }
i=137
i=138
i=139
i=140
i=141
i=142
i=143
i=144
i=145
子线程已经停止了,我要退出

用return也能停止线程,不过还是建议抛出异常的方法,因为可以继续往上抛出,让事件传播

原文地址:https://www.cnblogs.com/edison20161121/p/7954768.html