How can I simulate or write a code that would indicate that Java blocks a function till it has finished its execution. This way I will be able to show that Java has non-blocking I/O.
What I thought as my initial solution was to make an infinite loop but that didn't work as it will never finish its execution.
my other solution was to make a REST API and in that get request would delay and return something and think this might work but is there a native way to do it?
Here is the Java code below I want to delay the method fun2() without creating a new thread.
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");
}
}
Here is an equivalent JavaScript code to show that JavaScript has a non-blocking I/O. Want to simulate a similar kind of behavior in Java.
console.log("Hey");
setTimeout(() => {
console.log("there!")
},3000);
console.log("please help");
just want to write something similar in java but it should block till the execution of the setTimeout() function is complete.
CodePudding user response:
tl;dr
You can pause execution of a thread.
Thread
.sleep(
Duration.ofSeconds ( 7 )
)
Sleep
As discussed in comments, you can sleep the thread for a specific length of time. The static method Thread.sleep
method pauses execution of the current thread.
See Pausing Execution with Sleep in The Java Tutorials by Oracle Corp.
Thread.sleep( Duration.of… ( … ) ) ;
For example, sleep a half second.
Thread.sleep( Duration.ofMillis ( 500 ) ) ; // A half-second.
Or seven seconds.
Thread.sleep( Duration.ofSeconds ( 7 ) ) ; // Seven seconds.
Or half a day.
Thread.sleep( Duration.ofHours ( 12 ) ) ; // Twelve hours.
Prior to Java 19
Before Java 19 , you must pass a mere int
rather than a Duration
, as a count of milliseconds.
For example, here we pause for a half-second.
Thread.sleep( 500 ) ; // 500 milliseconds is a half-second.
In Java 8 through Java 18, no need for you to do the math to get milliseconds. Use Duration#toMillis
.
Thread.sleep( Duration.ofMinutes( 1 ).plusSeconds( 30 ).toMillis() ) ; // 1.5 minutes as a count of milliseconds.