Reputation: 1009
When i start some thread in my program, everything else is stopped.
This is my Thread code...
static Thread b1 = new Thread(new Builders());
b1.run();
System.out.println("done");
This is the 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 is started and the program wait for the end of the thread. I thought the main point of the threads is that the code can run simultaneously. Could someone please help me understand what I'm doing wrong.
Upvotes: 3
Views: 243
Reputation: 8774
You need to call the start()
method. The internal code of Thread will start a new operating system thread that calls your run()
method. By calling run()
yourself, you're skipping the thread-allocation code, and just running it in your current Thread.
Upvotes: 1
Reputation: 727057
This is because you are not starting a thread - instead, you are executing thread's code synchronously by calling run()
; you need to call start()
instead.
Better yet, you should use executors.
Upvotes: 2
Reputation: 62469
That's because threads are started with start()
, not run()
, which simply calls the run
method on the current thread. So it should be:
static Thread b1 = new Thread(new Builders());
b1.start();
System.out.println("done");
Upvotes: 8