Java 異步IO(1) 文件異步IO

大家寫過多線程都用過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();
		}
	}


發佈了62 篇原創文章 · 獲贊 138 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章