【发布时间】:2013-04-04 04:56:11
【问题描述】:
我只是想知道如何在单独的线程中控制控制台输入?
我有线程 A 和线程 B 和线程 C; B 和 C 他们都控制用户输入...问题是我不太确定如何在 B 和 C 线程之间切换 scanIn.nextLine(); 因为 B 似乎在线程 C 可以中断 B 之前循环了两次不必要的迭代 :(
主线程:
public class Main
{
private volatile ThreadGroup threadGroup=new ThreadGroup();//contains concurrent hash map...
private volatile TaskManager taskManager=new TaskManager(threadGroup);
private A a=new A(threadGroup);
private B b=new B(threadGroup,taskManager);
private C c=new C(threadGroup);
Main()
{
b.start();
threadGroup.add(a,"A");
threadGroup.add(b,"B");
threadGroup.add(c,"C");
}
public static void main(String args[]){new Main();}
}
TaskManager 方法 sn -p:
...
public synchronized void threadCMaybeCanBeStartedLater()
{
this.getThreadGroup().get("A").start();
}
...
thread 类似的代码(被覆盖的run方法调用):
public void loopIt()
{
Random generator = new Random();
A: while(!this.interrupted())
{
Thread.sleep(1000);
int i=generator.nextInt(100)+1;
int j=generator.nextInt(100)+1;
if(i==j){this.invokeC(); System.out.println("event : i==j");}
}
}
private void invokeC()
{
if(!this.getThreadGroup().get("C").isAlive())this.getThreadGroup().get("C").start();
}
线程 B 代码如:
public void loopIt() throws InterruptedException
{
Scanner scanIn = new Scanner(System.in);
B: while(!this.isInterrupted())
{
Thread.sleep(1000);
String command= scanIn.nextLine();
...
if(command.equals("a"))
{
System.out.println("a was entered");
this.getTaskManager().threadCMaybeCanBeStartedLater();//
continue;
}
if(command.equals("b"))
{
System.out.println("b was entered");
continue;
}
if(command.equals("c"))
{
System.out.println("c was entered");
continue;
}
else{System.out.println("no such command");}
}
}
线程C(run方法调用)
public void loopIt() throws InterruptedException
{
getThreadGroup().get("B").interrupt();
Scanner scanIn = new Scanner(System.in);
C: while(!this.isInterrupted())
{
Thread.sleep(1000);
String command= scanIn.nextLine();
...
if(command.equals("d"))
{
System.out.println("d was entered");
continue;
}
if(command.equals("e"))
{
System.out.println("e was entered");
this.interrupt();
break C;
}
if(command.equals("f"))
{
System.out.println("f was entered");
continue;
}
else{System.out.println("no such command");}
}
getThreadGroup().get("B").start();
}
...如您所见,主要代码概念(请参阅 A 线程 sn-p)是“您不知道 何时 线程 C 可以启动,但它何时启动你需要给它控制台";就这样;如果是 GUI 则没有问题,但类似控制台的应用程序会造成很大问题...
所以问题是……在这种情况下,如何立即从线程 C 中断/重新启动线程 B?
谢谢
【问题讨论】:
-
我想你发了两次
A。 -
我不知道这段代码有什么意义。
-
哦,天哪……这很明显;该代码正在测试一些传入事件“注入”的能力(在这种情况下,线程 A 扮演角色);如果线程 A 中发生了某些事情,那么它会从线程 B 为线程 C 获取控制台;主要问题是无法注入事件,因为 Scanner 永远阻塞或其他东西:( 我实际上也怀疑 System.in 静态性质,但我不确定......所以也许我不应该使用 Scanner 并且有一个alt 控制台输入解决方案,或者可能有更优化的方式来控制用户输入...
-
您可以从这里尝试解决方案:stackoverflow.com/questions/19130822/… 我已经修复(解决)中断
System.in读取操作无法被中断的问题,除非用户按下回车键。
标签: java multithreading io