Executing single thread execution

I was asked this question in an interview - not sure if that makes sense.

You have several threads of the same priority running and running, how do you make sure that a certain thread from them starts before completion?

You cannot use wait () and sleep () for other threads.

EDIT: Changing other threads is not allowed.

+4
source share
3 answers

It is deprecated and inherently unsafe (so you should never use it), but you could suspend() all the other threads, then join() to the one you want to complete first, and then resume() .

I'm not sure what they are for. If so, I would doubt neither my interview skills nor their knowledge of Java.

The β€œgood” decisions I can think of require at least a trivial change to the code that will be executed by the threads. Are you sure that changing these flows is not limited?

+1
source

has one join() thread another

+6
source

Since you are not allowed to modify threads, you will have to suspend pending threads and join () in the thread, which should finish first.


I will leave the following (I replied before an explanation about changing threads was added) for completeness, but with the specified limitations of the problem, these methods will be prohibited:

Ask each of the other threads to call join () on the thread that should finish first. This will make them wait until this thread completes, but using significantly less processor time than the sleep () loop.

 Thread first = new FirstThread(); Thread after1 = new AfterThread(first); Thread after2 = new AfterThread(first); 

In the launch method for AfterThread:

 first.join(); // Do the rest of this thread code 

You can also pass a timeout for the connection ().

An alternative method would be to create a lock that only a specific named thread can receive until this named thread receives and releases it once.

+2
source

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


All Articles