Answer the question
In order to leave comments, you need to log in
Why are threads in Java behaving so non-obvious?
Logically, when starting a thread, it should output what is inside the thread.
package com.company;
public class Main
{
static Egg mEgg;
public static void main(String[] args) {
mEgg = new Egg();
mEgg.start();
System.out.println("END");
}
}
class Egg extends Thread
{
@Override
public void run()
{
System.out.println("EGG !");
}
}
END
EGG!
Answer the question
In order to leave comments, you need to log in
It takes a certain amount of time to create a thread, and processor time must be allocated for its operation.
The Thread.start() method does not wait for the thread to be created, but immediately releases the thread that called it.
The main thread Main has already been created and is running, so it runs faster.
Egg is not a thread daemon, so java will wait for it to complete, i.e. displaying "EGG !"
Everything is clear and the result is correct.
What is the problem?
Why do you think it should be like this? And if you run two Eggs, which one will work first?
Why do you need Thread.join()?
Logically, when starting a thread, it should output what is inside the thread.
Logically, it shouldn't. Simply you did not understand logic of a multithreading yet.
There are no synchronizations, which means there are no guarantees that the side thread will print before the main one. If you want to wait for the end of the thread - use semaphores, for example. The result is necessary - use Future.
bromzh is right, I’ll add on my own that there is also a race condition and both threads can access the same file descriptor, in this case STDOUT - there is no guarantee that both threads will not write EGG and END at the same time and you won’t get EEGNG abracadabra! D ;)
Such behavior is typical for any multithreading, and Java has nothing to do with it.
To get rid of headaches, they use actor models and Share nothing approaches like all sorts of Akka, Greenlet'ov or processes in Erlang'e, but at a certain stage problems begin with them.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question