2017年9月5日 | Leave a comment 问题: 解决: 以下代码演示了在主线程中输入 0 /1 /2 控制线程的运行暂停退出 /* * 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); } } } } } 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 /* * 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); } } } }} 参考: