Junior — Middle
What methods can be used to organize thread execution order in a program?
sobes.tech AI
Answer from AI
To organize the order of thread execution in Java, several methods can be used:
join()method — allows one thread to wait for the completion of another. For example:
Thread t1 = new Thread(() -> {
// thread code
});
t1.start();
t1.join(); // current thread waits for t1 to finish
-
Synchronization using
synchronized— provides mutual exclusion, helping control access to shared resources and indirectly influencing execution order. -
Using
wait()andnotify()— allows threads to interact and wait for certain conditions. -
Classes from
java.util.concurrent:CountDownLatch— a thread waits until other threads perform certain actions.CyclicBarrier— allows a group of threads to wait for each other.Semaphore— limits the number of threads that can execute a certain section of code simultaneously.
-
Thread priorities — can be set using
setPriority(), but this does not guarantee strict order.
Example with join():
Thread t1 = new Thread(() -> System.out.println("Thread 1"));
Thread t2 = new Thread(() -> System.out.println("Thread 2"));
t1.start();
t1.join(); // wait for t1 to finish
t2.start();
In this example, thread t2 will only start executing after t1 has completed.