【问题标题】:How can I show Java has blocking I/O?如何显示 Java 具有阻塞 I/O?
【发布时间】:2022-10-07 17:25:37
【问题描述】:

我如何模拟或编写一个代码来指示 Java 阻塞一个函数,直到它完成它的执行。 通过这种方式,我将能够证明 Java 具有阻塞 I/O。

我最初的解决方案是创建一个无限循环,但这不起作用,因为它永远不会完成它的执行。

我的另一个解决方案是制作一个 REST API,在那个 get 请求中会延迟并返回一些东西,并认为这可能会起作用,但有没有一种本地方法可以做到这一点?

这是下面的 Java 代码,我想在不创建新线程的情况下延迟 fun2() 方法。

public class SetTimeOut {
     public static void  fun1(String str){
         System.out.println(str);
     }
    public static void fun2(String str){
       //how to make this function wait for 3 sec?
       System.out.println(str);  
    }
    public static void fun3(String str){
        System.out.println(str);
    }

    public static void main(String[] args) {
        fun1(\"Hello from fun1 is being called\");
        fun2(\"Hello from fun2 is being called\");
        fun3(\"Hello from fun3 is being called\");
    }
}

这是一个等效的 JavaScript 代码,用于显示 JavaScript 具有非阻塞 I/O。想要在 Java 中模拟类似的行为。

console.log(\"Hey\");

setTimeout(() => {
   console.log(\"there!\")
},3000);

console.log(\"please help\");
只是想在 java 中写一些类似的东西,但它应该阻塞直到 setTimeout() 函数的执行完成。
  • 使用Thread.sleep(5000) ?
  • 在主线程上?你能告诉我阻止 fun2() 5 秒吗 fun2()
  • 您只想在主线程中阻止您的代码,对吗?这应该能够阻塞线程。在此方法中以毫秒为单位传递时间,您应该一切顺利。

标签: java asynchronous


【解决方案1】:

tl;博士

您可以暂停线程的执行。

Thread
.sleep( 
    Duration.ofSeconds ( 7 ) 
)

睡觉

正如 cmets 中所讨论的,您可以让线程休眠特定的时间长度。静态方法Thread.sleep 方法暂停当前线程的执行。

请参阅 Oracle 公司的 The Java Tutorials 中的 Pausing Execution with Sleep。

Thread.sleep( Duration.of… ( … ) ) ;

例如,睡半秒。

Thread.sleep( Duration.ofMillis ( 500 ) ) ;  // A half-second.

或七秒。

Thread.sleep( Duration.ofSeconds ( 7 ) ) ;  // Seven seconds.

或者半天。

Thread.sleep( Duration.ofHours ( 12 ) ) ;  // Twelve hours.

在 Java 19 之前

在 Java 19+ 之前,您必须 pass a mere int 而不是 Duration,以毫秒计。

例如,这里我们暂停半秒。

Thread.sleep( 500 ) ;  // 500 milliseconds is a half-second. 

在 Java 8 到 Java 18 中,您无需计算毫秒数。使用Duration#toMillis。

Thread.sleep( Duration.ofMinutes( 1 ).plusSeconds( 30 ).toMillis() ) ;  // 1.5 minutes as a count of milliseconds.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2020-05-24
    • 2018-11-05
    • 2018-04-06
    • 2013-08-22
    相关资源
    最近更新 更多