package com.walker.infrastructure.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.TimeUnit; /** * 阻塞控制台的输入工具类

* 主要用来测试,可以让主线程阻塞,等待控制台输入内容
* 一旦输入了终止符,如:exit,线程继续。

* 也可以让主线程等待一段时间后继续运行。 * @author shikeying * */ public abstract class WaitConsoleInput { /** * 默认的输入终止符,默认为:exit */ public static final String DEFAULT_TERMINATOR = "exit"; private WaitConsoleInput(){} /** * 等待控制台输入内容,当前线程阻塞
* 使用默认的输入终止符:exit */ public static final void waitInput(){ waitInput(null); } /** * 等待控制台输入内容,当前线程阻塞
* 使用默认的输入终止符:exit * @param callback 输入回调实现,输入内容后自动调用该接口 */ public static final void waitInput(InputCallback callback){ waitInput(DEFAULT_TERMINATOR, callback); } /** * 等待控制台输入内容,当前线程阻塞
* 使用默认的输入终止符:exit * @param terminator 定义输入终止符,如:exit/quit等 * @param callback 输入回调实现,输入内容后自动调用该接口 */ public static final void waitInput(String terminator, InputCallback callback){ Assert.notNull(terminator, "terminator is required! e.g. " + DEFAULT_TERMINATOR); System.out.println("info:/> Please input something... '" + terminator + "' for terminate."); String input; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try{ while((input = reader.readLine()) != null){ if(input.trim().toLowerCase().equals(terminator.trim().toLowerCase())){ System.out.println("info:/> System Exit!"); break; } else if(callback != null){ System.out.println("info:/> execute callback: " + callback); callback.doInput(input); } else System.out.println("info:/> you input: " + input); System.out.print("\r"); } } catch(IOException ex){ ex.printStackTrace(); throw new Error("System error internal, terminated!"); } finally { if(reader != null){ try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block } } } } /** * 阻塞线程,等待指定的时间 * @param timeUnit 时间类型,如:TimeUnit.SECONDS, TimeUnit.MILLISECONDS * @param timeout 时间数量,如:60 */ public static final void waitInTimes(TimeUnit timeUnit, long timeout){ try { timeUnit.sleep(timeout); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println("Thread Interrupted: " + e.getMessage()); } } /** * 输入控制台内容后的回调接口定义

* 定义自己的业务逻辑来处理控制台输入内容。 * @author shikeying * */ public static interface InputCallback { /** * 处理输入内容 * @param input 输入控制台的字符串 */ void doInput(String input); } }