2

我是 JMS 和 OpenMQ 的新手。我在我的代码中同时使用了多线程,但是在执行代码时我得到了这个奇怪的输出。谁能解释一下多线程中的这些语句是如何执行的?

public void receiveData(){
    try {
        Hashtable<String, String> contextParams = new Hashtable<>();
        contextParams.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
        contextParams.put(Context.PROVIDER_URL, "file:///C:/jndiStorage");

        Context ctx = new InitialContext(contextParams); 

        QueueReceiver server = new QueueReceiver(ctx, "firstQueueConnectionFactory", "firstQueue");
        server.start();         
        System.out.println("staement 1");

    }catch (NamingException e) {
        System.out.println("JNDI Problem. Check used hostname and/or Glassfish configuration.");
        e.printStackTrace();
    }
}

我的另一种方法是这样的,它返回接收到的对象列表

public List<Ticket> getAllTickets() throws TicketException {
    receiveData();
    System.out.println("statement 2");
    return JMSLocalTicketStore.entrySet().stream().map(entry -> (Ticket) entry.getValue().clone()).collect(Collectors.toList());


}

扩展 Thread 类的 QueueReceiver 类是这样的:

public QueueReceiver(Context ctx, String connFactoryName, String queueName)
        throws NamingException {

    // Look up the connection factory object in the JNDI context provided
    connFactory = (ConnectionFactory) ctx.lookup(connFactoryName);

    // Look up the Destination in the JNDI context
    destination = (Destination) ctx.lookup(queueName);
}

private void startServer() {
    System.out.println("\t [RECEIVER]: Start waiting for messages");
    active = true;
    // Create JMS Context
    try (JMSContext jmsContext = connFactory.createContext()) {
        // Create a JMSConsumer to receive message
        JMSConsumer consumer = jmsContext.createConsumer(destination);
        while (active) {
            Ticket ticket = (Ticket) consumer.receiveBody(Ticket.class, 5000);

            // if no message is received with 5 secs messsage == null
            if (ticket != null) {
                System.out.println("Reveicer statement 1");
                stopServer();

            }else{
                empty();
            }
        }
    }
    System.out.println("\t [RECEIVER]: Stopped.");
}

public void empty(){
    active = false;
    System.out.println("No message in the OpenMQ");
}

public void stopServer() {
    active = false;
    System.out.println("\t [RECEIVER]: Stopping to listen for messages.");
}

@Override
public void run() {
    startServer();
}

}

我的输出是:

staement 1
statement 2
 [RECEIVER]: Start waiting for messages
Reveicer statement 1
 [RECEIVER]: Stopping to listen for messages.
 [RECEIVER]: Stopped.

为什么它没有在 getAllTickets() 语句 2 之前打印所有接收方语句

4

0 回答 0