Java中IO操作的阻塞和非阻塞实例

原创 秒速五厘米 2024-12-09 16:57 194阅读 0赞

在Java中,I/O(Input/Output)操作通常会涉及到阻塞和非阻塞两种模式。

  1. 阻塞模式:
    这种情况下,当线程调用一个需要等待I/O完成的操作(如read()write())时,该线程会被操作系统挂起,直到I/O操作完成或者超时。例如:
  1. public class BlockingIOExample {
  2. public static void main(String[] args) throws InterruptedException {
  3. Thread thread = new Thread(new Runnable() {
  4. @Override
  5. public void run() {
  6. // 阻塞读
  7. int bytesRead = 0;
  8. while (bytesRead < 1024) { // 直到读满1KB
  9. bytesRead += System.in.read();
  10. }
  11. }
  12. }));
  13. thread.start(); // 开始线程
  14. // 线程会在这里阻塞,直到read()操作完成或者超时
  15. }
  16. }
  1. 非阻塞模式:
    在这种情况下,当调用I/O操作时,如果当前没有足够的资源(如打开的文件描述符)进行I/O操作,那么操作系统不会挂起线程,而是直接返回一个错误码或超时。

例如:

  1. public class NonBlockingIOExample {
  2. public static void main(String[] args) throws IOException {
  3. // 非阻塞写
  4. int bytesWritten = System.out.write('H', 0, 1));
  5. if (bytesWritten == -1) { // 操作失败,返回错误码
  6. System.err.println("Error writing to stdout: " + strerror(errno));
  7. return;
  8. }
  9. // 然后我们可以直接打印出写入的内容
  10. String output = new String(bytesWritten, 'US-ASCII'));
  11. System.out.println(output); // 输出:H
  12. }
  13. }

以上就是Java中I/O操作阻塞和非阻塞的实例。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,194人围观)

还没有评论,来说两句吧...

相关阅读