0

I am trying to figure out how Thread.sleep works, so I create the following piece of code:

 public static void main() {

        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    Thread.sleep(1000);
                    System.out.println("Middle");
                } catch (InterruptedException e) {
                }
            }
        };

        System.out.println("Before");
        Thread t2 = new Thread(runnable);
        t2.start();
        System.out.println("After");

However, it only prints Before and After in the console and skips the Middle.

So I am wondering whether this Thread.sleep will break the Runnable part??

Skydidi
  • 21
  • 2
  • 2
    What do you mean "skips the `Middle`"? Your code should print out "Before", then "After", and then after one second it should print out "Middle". – Slaw Jul 25 '21 at 15:03
  • Cannot reproduce. Output is exactly what Slaw said. – luk2302 Jul 25 '21 at 15:07
  • Thanks, guys, I got the point, the Junit kill the process before the thread t2 end – Skydidi Jul 25 '21 at 15:17
  • 2
    For future reference, please make sure you provide a [mre] that demonstrates the problem. There is no reference to JUnit in your code or question and, as you've already discovered, that potentially changes things. – Slaw Jul 25 '21 at 15:23

2 Answers2

2

On my machine output of your code is:

Before
After
Middle

If you want to print Middle before After you need to add t2.join() method call right after t2.start().
Join method explanation.

vszholobov
  • 2,133
  • 1
  • 8
  • 23
  • Thanks vszholobov, I just realised the sleep is not blocking the process, but release the resource to other thread – Skydidi Jul 25 '21 at 15:18
-1

Use join () to make your main thread wait till your thread (t2) execution finishes.

    public static void main(String[] args) throws InterruptedException {
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println("Middle");
            } catch (InterruptedException e) {
            }
        }
    };

    System.out.println("Before");
    Thread t2 = new Thread(runnable);
    t2.start();
    t2.join();
    System.out.println("After");

Output: Before Middle After

Refer to this post to know about join() : What does this thread join code mean?

Refer to this post to know about the main thread: When does the main thread stop in Java?

Sitaram P
  • 7
  • 3