[我试图了解在Java中实现一个程序的正确方法是,该程序不断从控制台读取消息,并根据消息执行不同的操作。
目前,我已经创建了两个线程,一个线程负责从控制台读取消息,另一个线程执行操作,这些操作并非在所有情况下都必须停止读取控制台输入的内容
这是线程1的代码,它从主线程开始,然后在控制台中继续其读取周期。
public class Thread1 implements Runnable{
public void run() {
String input;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("Insert command:");
//edited part
try {
input = scanner.nextLine();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
scanner.close();
break;
}
String[] strings = input.split(" ");
switch (strings[0]) {
case "something":
//do something
break;
...
case "login":
//something...
//here I start second thread
Sender senderTask = new Sender(Thread.currentThread());
Thread senderThread = new Thread(senderTask);
senderThread.start();
break;
//this thread now does not end but waits for other input messages
default:
break;
}
}
}
}
senderThread执行操作,有时我不希望thread1继续读取控制台输入,它停留在scanner.nextLine()
上等待输入。因此,我考虑过使用thread.stop()
停止它是否正确?有没有更好的办法?这是senderThread代码
public class Sender implements Runnable {
private Thread thread1;
public Sender(Thread thread1) {
this.thread1 = thread1;
}
public void run() {
while(true) {
//in short here I am waiting for an udp package, if it arrives I don't want to read the messages from the console anymore
//so somehow I end thread1 and I have to try to close the scanner, is it right to do it this way?
//I know stop() is deprecated, is there something else that I can use?
//edited part
thread1.interrupt();
//here I create a new scanner because after I received the udp packet
//I want to read a message from the console that is different from those that go to the switch case of thread1
Scanner scanner = new Scanner(System.in);
String msg = scanner.nextLine();
if(msg.equals("y")){
//do something
break;
}
}
if(thread1.isAlive()==false) {
thread1.start();
}
}
}
最后,我再次启动thread1,它从控制台读取消息
使用Thread.interrupt()。如果它在某个长时间运行的循环中受阻,它将导致该线程引发异常。捕获InterruptedException并从该线程返回。
这假定您要中断的方法检查中断标志(thread.interrupted())。我认为所有长时间运行的Java API方法都可以做到这一点(例如Scanner.nextLine(),thread.wait()以及从端口读取的任何内容),但是请记住,如果您有一个循环在旋转,则应检查被中断的标志,当您看到它时,自己抛出一个InterruptedException。