Java main code stops when thread starts

When I start some thread in my program, everything else stops.

This is my theme code ...

static Thread b1 = new Thread(new Builders());
b1.run();
System.out.println("done");

This is a class Builders.

public class Builders implements Runnable {

    static boolean busy=false;
    Random r = new Random();

    public void run() {
        try{
            busy=true;
            System.out.println("ready");
            Thread.sleep(9999);
            busy=false;
            System.out.println("done");
        }
        catch(Exception e){
        }
    }
}

When I run the program, the thread starts and the program waits for the end of the thread. I thought that the main theme of threads is that code can work simultaneously. Can someone please help me understand what I'm doing wrong.

+3
source share
3 answers

This is because threads start with start(), rather than run(), which simply calls the method runin the current thread. Therefore, it should be:

static Thread b1 = new Thread(new Builders());
b1.start();
System.out.println("done");
+8
source

, - , run(); start().

, executors.

+2

You need to call a method start(). Thread's internal code will start a new operating system thread that calls your method run(). By calling it run()yourself, you skip the thread allocation code and simply run it in the current thread.

+1
source

All Articles