大家寫過多線程都用過java.util.concurrent包,自己創建線程池,自己實現run 或者call接口創建線程類,之後提交給線程池運行。
之前大家讀寫文件,必須得等待IO完成。如果要想節約時間,還得自己實現上面多線程那一套。今天剛知道異步IO這個東西,不用自己實現多線程了。下面是示例代碼:
public static void asynchronousFileIO()
{
Path path = Paths.get("resource/Stopword.txt");
try
{
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);
ByteBuffer buffer = ByteBuffer.allocate(1000);
Future<Integer> future = channel.read(buffer, 0);
while (!future.isDone())
{
System.out.println("Do others...");
}
Integer number = future.get();
System.out.println("Read " + number + " content : " + new String(buffer.array()));
channel.close();
} catch (IOException | InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}