热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java中的阻塞方法

Java中的阻塞方法原文:https://www.geeksf

Java 中的阻塞方法

原文:https://www.geeksforgeeks.org/blocking-methods-in-java/

java 中的阻塞方法是阻塞线程直到其操作完成的一组特定方法。因此,他们将不得不阻塞当前线程,直到满足完成任务的条件。因为在本质上,这些方法是阻塞所谓的阻塞方法。例如,InputStreamread()方法会阻塞,直到所有 InputStream 数据都被完全读取。下面是一些最常见的 Java 阻塞方法:


  1. Invokedwait (): Wait for the event scheduler thread to execute the code.

  2. InputStream.read (): It blocks until the input data is available, throws an exception, or detects the end of the stream.

  3. ServerSocket.accept (): Listen for inbound Java socket connection and block it until the connection is established.

  4. Countdown.await (): Make the current thread wait until the latch count is zero, unless the thread is interrupted.

阻塞方法有几个缺点:


  • Blocking technology poses a great threat to the scalability of the system. A classic blocking solution includes the method of reducing blocking and using multithreading to serve multiple customers.

  • Design is the most important aspect, because even if a multithreaded system cannot reach a certain point, a poorly designed system can only support hundreds or thousands of threads, because the number of JVM threads is limited.

实施:

在下面的示例中,在执行第一个 print 语句后,程序将被第二个 print 语句阻止,直到控制台中输入一些字符。然后单击 enter,因为 read()会阻止该方法,直到某些输入可读为止。

例 1:

Java


// Java Program to illsutare Blocking methods
// Importing all input output classes
import java.io.*;
// Class
class GFG {
   // main driver method
   public static void main(String args[]) throws FileNotFoundException, IOException 
   {
     // Print statement
     System.out.println("GFG");
     int result;
     result = System.in.read();
     // Print statement
     System.out.println("Geeks for Geeks");
   } 
}

输出

GFG
Geeks for Geeks

例 2:

在这个例子中,当一个线程在开始工作之前需要等待其他线程时,使用 CountDownLatch.await()。倒计时()方法减少计数,等待()方法阻塞,直到计数= 0。

爪哇


// Java Program to illsutare Blocking methods
// Importing all input output classes
import java.io.*;
// Importing concurrent CountDownLatch class
// from java.util package
import java.util.concurrent.CountDownLatch;
// Class
class GFG {
    // Main driver method
    public static void main(String args[])
        throws InterruptedException
    {
        // Let us create task that is going to wait
        // for five threads before it starts
        CountDownLatch latch = new CountDownLatch(4);
        // Creating threads of Person type
        // Custom parameter inputs
        Person p1 = new Person(1500, latch, "PERSON-1");
        Person p2 = new Person(2500, latch, "PERSON-2");
        Person p3 = new Person(3500, latch, "PERSON-3");
        Person p4 = new Person(4500, latch, "PERSON-4");
        Person p5 = new Person(5500, latch, "PERSON-5");
        // Starting the thread
        // using the start() method
        p1.start();
        p2.start();
        p3.start();
        p4.start();
        p5.start();
        // Waiting for the four threads
        // using the latch.await() method
        latch.await();
        // Main thread has started
        System.out.println(Thread.currentThread().getName()
                           + " has finished his work");
    }
}
// Class 2
// Helper class extending Thread class
// To represent threads for which the main thread waits
class Person extends Thread {
    // Member variables of this class
    private int delay;
    private CountDownLatch latch;
    // Method of this class
    public Person(int delay, CountDownLatch latch,
                  String name)
    {
        // super refers to parent class
        super(name);
        // This keyword refers to current object itself
        this.delay = delay;
        this.latch = latch;
    }
    @Override public void run()
    {
        // Try block to check for exceptions
        try {
            Thread.sleep(delay);
            latch.countDown();
            // Print the current thread by getting its name
            // using the getName() method
            // of whose work is completed
            System.out.println(
                Thread.currentThread().getName()
                + " has finished his work");
        }
        // Catch block to handle the exception
        catch (InterruptedException e) {
            // Print the line number where exception occured
            // using the printStackTrace() method
            e.printStackTrace();
        }
    }
}

输出

PERSON-1 has finished his work
PERSON-2 has finished his work
PERSON-3 has finished his work
PERSON-4 has finished his work
main has finished his work
PERSON-5 has finished his work


推荐阅读
  • 从 .NET 转 Java 的自学之路:IO 流基础篇
    本文详细介绍了 Java 中的 IO 流,包括字节流和字符流的基本概念及其操作方式。探讨了如何处理不同类型的文件数据,并结合编码机制确保字符数据的正确读写。同时,文中还涵盖了装饰设计模式的应用,以及多种常见的 IO 操作实例。 ... [详细]
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • 本文详细介绍了Akka中的BackoffSupervisor机制,探讨其在处理持久化失败和Actor重启时的应用。通过具体示例,展示了如何配置和使用BackoffSupervisor以实现更细粒度的异常处理。 ... [详细]
  • 本文详细解析了Python中的os和sys模块,介绍了它们的功能、常用方法及其在实际编程中的应用。 ... [详细]
  • 本题探讨如何通过最大流算法解决农场排水系统的设计问题。题目要求计算从水源点到汇合点的最大水流速率,使用经典的EK(Edmonds-Karp)和Dinic算法进行求解。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 1.如何在运行状态查看源代码?查看函数的源代码,我们通常会使用IDE来完成。比如在PyCharm中,你可以Ctrl+鼠标点击进入函数的源代码。那如果没有IDE呢?当我们想使用一个函 ... [详细]
  • 主要用了2个类来实现的,话不多说,直接看运行结果,然后在奉上源代码1.Index.javaimportjava.awt.Color;im ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • 使用Vultr云服务器和Namesilo域名搭建个人网站
    本文详细介绍了如何通过Vultr云服务器和Namesilo域名搭建一个功能齐全的个人网站,包括购买、配置服务器以及绑定域名的具体步骤。文章还提供了详细的命令行操作指南,帮助读者顺利完成建站过程。 ... [详细]
  • Scala 实现 UTF-8 编码属性文件读取与克隆
    本文介绍如何使用 Scala 以 UTF-8 编码方式读取属性文件,并实现属性文件的克隆功能。通过这种方式,可以确保配置文件在多线程环境下的一致性和高效性。 ... [详细]
author-avatar
笑竹舞
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有