Java中IO操作的阻塞和非阻塞实例
在Java中,I/O(Input/Output)操作通常会涉及到阻塞和非阻塞两种模式。
- 阻塞模式:
这种情况下,当线程调用一个需要等待I/O完成的操作(如read()
或write()
)时,该线程会被操作系统挂起,直到I/O操作完成或者超时。例如:
public class BlockingIOExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 阻塞读
int bytesRead = 0;
while (bytesRead < 1024) { // 直到读满1KB
bytesRead += System.in.read();
}
}
}));
thread.start(); // 开始线程
// 线程会在这里阻塞,直到read()操作完成或者超时
}
}
- 非阻塞模式:
在这种情况下,当调用I/O操作时,如果当前没有足够的资源(如打开的文件描述符)进行I/O操作,那么操作系统不会挂起线程,而是直接返回一个错误码或超时。
例如:
public class NonBlockingIOExample {
public static void main(String[] args) throws IOException {
// 非阻塞写
int bytesWritten = System.out.write('H', 0, 1));
if (bytesWritten == -1) { // 操作失败,返回错误码
System.err.println("Error writing to stdout: " + strerror(errno));
return;
}
// 然后我们可以直接打印出写入的内容
String output = new String(bytesWritten, 'US-ASCII'));
System.out.println(output); // 输出:H
}
}
以上就是Java中I/O操作阻塞和非阻塞的实例。
还没有评论,来说两句吧...