问题:
解决:
以下代码演示了在主线程中输入 0 /1 /2 控制线程的运行暂停退出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package threadwait; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author sihai */ public class App { private static final Logger LOG = Logger.getLogger(App.class.getName()); static Integer statu = 0;//0 :running ; 1:wait ; 2:quit public static void main(String[] argv) { List<T> list = new ArrayList<>(); for (int i = 0; i < 10; ++i) { final T t = new T(); t.start(); list.add(t); } final Scanner sc = new Scanner(System.in); while (true) { System.out.println("please input command number (0:run 1:pause 2:exit)"); statu = Integer.parseInt(sc.next()); if (statu != 1) { list.forEach(t -> { synchronized (t) { t.notify(); } }); if (statu == 2) { break; } } } } public static class T extends Thread { @Override public void run() { while (statu != 2) { if (statu == 1) { try { synchronized (this) { wait(); } } catch (InterruptedException ex) { LOG.log(Level.SEVERE, null, ex); } } System.out.println("do something"); try { Thread.sleep(1000); } catch (InterruptedException ex) { LOG.log(Level.SEVERE, null, ex); } } } } } |
参考: