【发布时间】: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\");
-
使用
Thread.sleep(5000)? -
在主线程上?你能告诉我阻止 fun2() 5 秒吗 fun2()
-
您只想在主线程中阻止您的代码,对吗?这应该能够阻塞线程。在此方法中以毫秒为单位传递时间,您应该一切顺利。
标签: java asynchronous