在带有异步通信服务器的服务器中使用Future对象
import java.io.IOException; import java.net.InetSocketAddress; /* from 时 代 J a v a 公 众 号 */ import java.net.SocketOption; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class Main { public static void main(String[] args) { try {//N o w J a v a . c o m 提供 final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open(); InetSocketAddress address = new InetSocketAddress("localhost", 5000); listener.bind(address); Future<AsynchronousSocketChannel> future = listener.accept(); AsynchronousSocketChannel worker = future.get(); while (true) { // Wait System.out.println("Server: Receiving ..."); ByteBuffer buffer = ByteBuffer.allocate(32); Future<Integer> readFuture = worker.read(buffer); Integer number = readFuture.get();