D
D
Dmitry Ilnitsky2015-05-06 16:32:04
Java
Dmitry Ilnitsky, 2015-05-06 16:32:04

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 !");
    }
}

But it comes out like this.
END
EGG!

Answer the question

In order to leave comments, you need to log in

5 answer(s)
E
Evhen, 2015-05-07
@DaleMartinWatson

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 !"

O
one pavel, 2015-05-06
@onepavel

Everything is clear and the result is correct.
What is the problem?

V
Vladimir Abramov, 2015-05-06
@kivsiak

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()?

B
bromzh, 2015-05-06
@bromzh

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.

Y
Yuri Yarosh, 2015-05-06
@voidnugget

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 question

Ask a Question

731 491 924 answers to any question