如果是以下方式,我的代码工作正常。
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;
}
}
编辑:以下是已编辑的代码。当scan.nextInt()值输入1时,finished = 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();
}
}
}
}
答案 0 :(得分:0)
int stop = input.nextInt()是一个阻塞调用,所以它只执行一次ClassA runnable然后等待输入。
您需要将输入代码移动到另一个线程,因此它不会阻止ClassA的执行。
也许更好的选择是只有一次执行ClassA并在其中有另一个while(true)循环。