3种下载文件程序的思考,为何使用NIO进行异步网络通讯(五)

2014-11-24 01:22:42 · 作者: · 浏览: 10
// 往输出文件中去写了
if (count < bufferSize) {

byte[] overByte = new byte[count];

for (int index = 0; index < count; index++) {
overByte[index] = buffer.get(index);
}

fout.write(overByte);
} else {
fout.write(buffer.array());
}

} else {

// 关闭客户端通道
client.close();

// 退出大循环
break FOR;
}
}
}
}

// 计算时间
double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
System.out.println("Thread " + index + " downloaded " + total
/ 1024 + "kbytes in " + last + "s.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) throws IOException {

long startTime = System.currentTimeMillis();

// 启用线程池
ExecutorService exec = Executors.newFixedThreadPool(SIZE);
for (int index = 1; index <= SIZE; index++) {
exec.execute(new Download(index));
}
exec.shutdown();

long endTime = System.currentTimeMillis();

long timeLong = endTime - startTime;

System.out.println("下载时间:" + timeLong);

}
}

效果和上一个程序的效果差不多,只是时间上和内存资源占有率上有所提高,当然本机仅仅启动了几个线程,如果客户端启动更多线程,NIO的方式节约资源的效果是明显的,宕机概率小于阻塞IO方式很多。
5. 总结
其实NIO想写得更多,但是看到网络上已经有很多资料了,就不再展开了,非一篇所能尽述的了的。当然了,NIO也是有场景的,比如适合与长连接的请求,以为NIO维护管道、缓存块、时间选择器等等也需要资源消耗的,而且比传统IO的对象们要重量级。所以原始IO也并不是一无是处,现在还是有很多socket中间件还是已然使用第二种方式。
代码在附件中~~~