我有一个线程可以通过在控制台中按Enter键来停止。因此,我需要模拟一段时间(例如2秒)后按下Enter键的过程。我猜我必须创建自己的InputStream,将System.lineSeparator的字节放入控制台或其他内容,然后更改标准输入流System.setIn()
这是停止线程的类
public class TestThread {
Thread thread = new Writer();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
TestThread testThread = new TestThread();
testThread.start();
while (true) {
if (in.nextLine().equals("")) {
testThread.end();
break;
}
}
}
public void start(){
thread.start();
}
public void end(){
thread.interrupt();
}
private class Writer extends Thread{
@Override
public void run() {
try {
while (!isInterrupted()) {
sleep(1000);
System.out.println("Something");
}
} catch (InterruptedException e) {
}
}
}
}
这是我需要按Enter键进行模拟的课程
public class TestMain {
public static void main(String[] args) {
//here we must to replace standard input stream by our's
//System.setIn(OUR_INPUT_STREAM);
Thread thread = new Thread(()->{TestThread.main(null); });
thread.start();
//here will be the delay, Thread.sleep(2000); for example
//and here we must simulate pressing the Enter button
}
}