Contents
What is thread priority How thread priority are set and changed?
The thread priority determines when the processor is provided to the thread as well as other resources. It can be changed using the method setPriority() of class Thread.
How do you handle multiple threads?
This approach provides more flexibility in handling multiple threads created using available methods in Thread class.
- You will need to override run( ) method available in Thread class.
- Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method.
How wait for all threads to finish with ExecutorService?
ExecutorService – Waiting for Threads to Finish
- Waiting for existing threads to complete their execution can be achieved by using the awaitTermination() method.
- A CountDownLatch is useful when we need a mechanism to notify one or more threads that a set of operations performed by other threads has finished.
How can we make threads to run one after another in sequence?
We can use use join() method of thread class. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join, and T2 calls T1.
Which method is used to make main thread to wait for all child threads?
1. Which of this method can be used to make the main thread to be executed last among all the threads? Explanation: By calling sleep() within main(), with long enough delay to ensure that all child threads terminate prior to the main thread.
How are 3 threads to print alternate values in sequence?
Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values. One condition is i don’t want to use synchronize.
How to print even numbers using two threads?
Approach: The idea is to create two threads and print even numbers with one thread and odd numbers with another thread. Below are the steps: Create two threads T1 and T2 using the below syntax, where T1 and T2 are used to print odd and even numbers respectively.
How to print the natural sequence of integers?
Print the natural sequence of integers starting from 1 from a set of 3 (or more) threads that take turns in a round robin fashion; such that, thread 1 prints 1, thread 2 prints 2, thread 3 prints 3 and then thread 1 prints 4 and so on. I have seen people writing crazy and complex logic to switch between threads.
How to print even numbers in increasing order?
If the counter is even in the Thread T1, then wait for the thread T2 to print that even number. Otherwise, print that odd number, increment the counter and notify to the Thread T2 using the function notify ().