Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the main thread get control immediately after calling some thread's start() method?

For example :

public class Example1 {

    public static void main(String[] args) {
        Loop loop = new Loop();
        loop.start(); //printing "Before start"
        System.out.println("After start");
    }
}

Can be a situation that the loop's run method finishes before the execution of the last line that prints "After Start"?

like image 531
sharon182 Avatar asked Apr 17 '15 08:04

sharon182


People also ask

What happens when thread's start () method is called?

New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed.

What is the difference between calling start () and run () method of thread?

In Summary only difference between the start() and run() method in Thread is that start creates a new thread while the run doesn't create any thread and simply executes in the current thread like a normal method call.

How do you control main thread?

The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called.

When two threads are waiting to gain control each other is called?

With locking, deadlock happens when threads acquire multiple locks at the same time, and two threads end up blocked while holding locks that they are each waiting for the other to release.


2 Answers

Once you start multi-threading, you would be wise to drop all assumptions you have about the order in which threads will run.

If it's important, you can use synchronizing operations but, without them, all bets are off.

like image 51
paxdiablo Avatar answered Oct 26 '22 08:10

paxdiablo


Yes, you have no control over how the threads are executed/scheduled by the JVM.

If you want to introduce some kind of ordering (execute the two threads in sequence) the most straightforward way to do it would be to use one of the Lock objects that Java provides.

like image 22
uraimo Avatar answered Oct 26 '22 07:10

uraimo