如果采用以下方式,我的代码可以正常工作。
Scanner input = new Scanner(System.in);
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 3; i++)
{
Runnable worker = new ClassA();
executor.execute(worker);
}
相反,我想在
while(true)
循环中连续运行,并在用户输入1时中断循环。我尝试了以下方法,但是它不起作用。它不是连续运行,而是在此行停止(阻止)int stop = input.nextInt();
有人可以告诉我错误在哪里。无论这是否是正确的方法,如果不是,请提出替代方案。我在A类中的代码连接到jms queue
,并应不断从队列中读取消息。Scanner input = new Scanner(System.in);
ExecutorService executor = Executors.newFixedThreadPool(2);
while(true)
{
Runnable worker = new ClassA();
executor.execute(worker);
int stop = input.nextInt();
if(stop == 1) {
break;
}
}
编辑:以下是已编辑的代码。当输入scanner.nextInt()值1时,完成= true。虽然(!finished)循环中断,但其中的代码未执行,但我的Consumer类仍在连续运行。
public class ScannerProblem {
public static boolean finished = false;
static class Listener implements Runnable {
Scanner scanner = new Scanner(System.in);
@Override
public void run() {
while (true) {
System.out.println("scanning");
if (scanner.nextInt() == 1) {
System.out.println("scanning finished");
finished = true;
return;
} else {
System.out.println("scanned something strange");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Consumer implements Runnable {
javax.jms.Connection jmsConnection = null;
private static ProcessRequest processRequest = new ProcessRequest();
@Override
public void run() {
ActiveMQConnection con = new ActiveMQConnection();
jmsConnection = con.openTcpConnection();
try {
String json = null;
Session session = jmsConnection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("Upload_Queue");
MessageConsumer consumer = session.createConsumer(queue);
TextMessage message = (TextMessage) consumer.receive();
System.out.println("Message #" + ": " + message.getText());
json = message.getText();
processRequest.upload(json);
System.out.println("Thread ID: " + Thread.currentThread().getId());
if (jmsConnection != null) {
jmsConnection.close();
}
Thread.sleep(5000);
}
catch(JMSException e) {
e.printStackTrace();
}
catch(InterruptedException e){
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(new Listener());
while (!finished) {
System.out.println("finished::"+finished);
pool.submit(new Consumer());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最佳答案
int stop = input.nextInt()是阻塞调用,因此它仅执行一次可运行的ClassA,然后等待输入。
您需要将输入代码移至另一个线程,以免阻塞ClassA的执行。
也许更好的选择是仅执行一个ClassA执行,并在其中执行另一个while(true)循环。
关于java - Scanner.nextInt()块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34946088/