热门标签 | 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


推荐阅读
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • javascript  – 概述在Firefox上无法正常工作
    我试图提出一些自定义大纲,以达到一些Web可访问性建议.但我不能用Firefox制作.这就是它在Chrome上的外观:而那个图标实际上是一个锚点.在Firefox上,它只概述了整个 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 成功安装Sabayon Linux在thinkpad X60上的经验分享
    本文分享了作者在国庆期间在thinkpad X60上成功安装Sabayon Linux的经验。通过修改CHOST和执行emerge命令,作者顺利完成了安装过程。Sabayon Linux是一个基于Gentoo Linux的发行版,可以将电脑快速转变为一个功能强大的系统。除了作为一个live DVD使用外,Sabayon Linux还可以被安装在硬盘上,方便用户使用。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Android源码深入理解JNI技术的概述和应用
    本文介绍了Android源码中的JNI技术,包括概述和应用。JNI是Java Native Interface的缩写,是一种技术,可以实现Java程序调用Native语言写的函数,以及Native程序调用Java层的函数。在Android平台上,JNI充当了连接Java世界和Native世界的桥梁。本文通过分析Android源码中的相关文件和位置,深入探讨了JNI技术在Android开发中的重要性和应用场景。 ... [详细]
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社区 版权所有