JAVA中的fire和foget方法,方法则不需要等待

时间:2013-08-29 00:42:06

标签: java asynchronous methods

我有一个等待UDP包的自定义线程。收到后,我希望这个线程继续运行,只是将信息发送到另一个方法。我检查了@Asynchronous表示法,但这似乎只适用于javaEE。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

“我有一个等待UDP包的自定义线程” - 这是你的答案,有另一个线程可以处理它们。

我建议您查看Executors。这样,您可以让多个线程处理传入的数据包而无需自己管理

答案 1 :(得分:0)

另一种方法是使用队列。

等待UDP数据包的线程将找到的数据包放到BlockingQueue上。另一个线程不断轮询该队列并处理它找到的任何内容。

例如:

public class UdpReceivingThread extends Thread {

    private final BlockingQueue<UdpPacket> queue;

    public UdpReceivingThread(BlockingQueue<UdpPacket> queue) {
        this.queue = queue;
    }


    @Override
    public void run() {
        while (true) {
            UdpPacket packet = listenForPacket();
            queue.put(packet);
        }
    }
}

public class ProcessingThread extends Thread {

    private final BlockingQueue<UdpPacket> queue;

    public ProcessingThread(BlockingQueue<UdpPacket> queue) {
        this.queue = queue; // Same queue instance as in UdpReceivingThread instances!
    }

    @Override
    public void run() {
        while(true) {
            UdpPacket packet = queue.take();
            process(packet);
        }
    }
}     

请注意,此方法肯定与使用Executor有关 - Executor实际上使用BlockingQueue来管理Runnables,Runnables包装方法调用以处理UDP数据包。这只是另一种方式。

答案 2 :(得分:0)

您可以这样做:

private static final ExecutorService threadPool = Executors.newCachedThreadPool();  
InetAddress address = InetAddress.getByName("hostname");
while(true){  
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
    threadPool.execute(new Runnable(){  
         public void run(){  
           processPacket(clientConnection);   // write a method to do the packet processing
       }
    );               
}