Java multithreading

I have a main method with something like:

A a = new A();
a.start();

B b = new B();
b.start();

B works with the file that creates a.start, so a.start () should finish first. However, a.start () starts a multi-threaded task, and b.start () is executed before it is executed.

  • Why does the main thread starting a.start () exit the method before it finishes?
  • What is a good way to make sure b.start () does not start before a.start () is executed?

Thank!

+3
source share
2 answers

It sounds like you don’t have to do these tasks in separate threads at all, but if you really want you to be able to do something like this:

A a = new A();
a.start();
a.join(); // Will wait until thread A is done

B b = new B();
b.start();
b.join(); // Will wait until thread B is done

, A B Thread, Runnable Thread (Runnable).start().

Executor A B Runnable ( Thread). :

ExecutorService ex = Executors.newSingleThreadExecutor();
ex.execute(new A());
ex.execute(new B());

A B .

+13

Source: https://habr.com/ru/post/1786637/


All Articles