java7 NIO2(8)The Asynchronous Channel API 异步通道API(三)

2014-11-24 11:01:30 · 作者: · 浏览: 3
ByteBuffer buffer = ByteBuffer
.allocateDirect(ThreadLocalRandom.current()
.nextInt(100, 200));
asynchronousFileChannel.read(buffer, ThreadLocalRandom
.current().nextInt(0, 100));
return buffer;
}
};
Future future = taskExecutor.submit(worker);
list.add(future);
}
// this will make the executor accept no new threads
// and finish all existing threads in the queue
taskExecutor.shutdown();
// wait until all threads are finished
while (!taskExecutor.isTerminated()) {
// do something else while the buffers are prepared
System.out
.println("Counting sheep while filling up some buffers!So far I counted: "
+ (sheeps += 1));
}
System.out.println("\nDone! Here are the buffers:\n");
for (Future future : list) {
ByteBuffer buffer = future.get();
System.out.println("\n\n" + buffer);
System.out
.println("______________________________________________________");
buffer.flip();
System.out.print(Charset.forName(encoding).decode(buffer));
buffer.clear();
}
} catch (Exception ex) {
System.err.println(ex);
}
}
//异步server socket channel io处理示例
public static void asyServerSocketChannel() {
//使用threadGroup
// AsynchronousChannelGroup threadGroup = null;
// ExecutorService executorService = Executors
// .newCachedThreadPool(Executors.defaultThreadFactory());
// try {
// threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
// } catch (IOException ex) {
// System.err.println(ex);
// }
// AsynchronousServerSocketChannel asynchronousServerSocketChannel =
// AsynchronousServerSocketChannel.open(threadGroup);
final int DEFAULT_PORT = 5555;
final String IP = "127.0.0.1";
ExecutorService taskExecutor = Executors.newCachedThreadPool(Executors
.defaultThreadFactory());
// create asynchronous server socket channel bound to the default group
try (AsynchronousServerSocketChannel asynchronousServerSocketChannel = AsynchronousServerSocketChannel
.open()) {
if (asynchronousServerSocketChannel.isOpen()) {
// set some options
asynchronousServerSocketChannel.setOption(
StandardSocketOptions.SO_RCVBUF, 4 * 1024);
asynchronousServerSocketChannel.setOption(
StandardSocketOptions.SO_REUSEADDR, true);
// bind the server socket channel to local address
asynchronousServerSocketChannel.bind(new InetSocketAddress(IP,
DEFAULT_PORT));
// display a waiting message while ... waiting clients
System.out.println("Waiting for connections ...");
while (true) {
Future asynchronousSocketChannelFuture = asynchronousServerSocketChannel.accept();