C
C
Core Java
Search…
Pause Thread Execution

Thread Scheduling:

A processor’s time is usually time-sliced to allow multiple threads to run, with each thread using one or more time slices. A thread scheduler might suspend a running thread and move it to the ready state, executing another thread from the ready queue. Thread scheduling is specific to JVM implementation and beyond the control of an application programmer. The scheduler moves a thread from the READY state to RUNNING and vice versa, to support concurrent processing of threads.

Thread Priorities:

  1. 1.
    Remember that all the threads carry normal priority when a priority is not specified.
  2. 2.
    Priorities can be specified from 1 to 10. 10 being the highest, 1 being the lowest priority and 5 being the normal priority.
  3. 3.
    Remember that the thread with highest priority will be given preference in execution. But there is no guarantee that it will be in running state the moment it starts.
  4. 4.
    Always the currently executing thread might have the higher priority when compared to the threads in the pool who are waiting for their chance.
  5. 5.
    It is the thread scheduler which decides what thread should be executed.
  6. 6.
    t.setPriority() can be used to set the priorities for the threads.
  7. 7.
    Remember that the priorities should be set before the threads start method is invoked.
  8. 8.
    You can use the constants, MIN_PRIORITY,MAX_PRIORITY and NORM_PRIORITY for setting priorities.
1) yield() :
Theoretically, to ‘yield’ means to let go, to give up, to surrender. A yielding thread tells the virtual machine that it’s willing to let other threads be scheduled in its place. This indicates that it’s not doing something too critical. Note that it’s only a hint, though, and not guaranteed to have any effect at all.
yield() is defined as following in Thread.java.
1
/**
2
* A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore
3
* this hint. Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilize a CPU.
4
* Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
5
*/
6
7
public static native void yield();
Copied!
Let’s list down important points from above definition:
  • Yield is a Static method and Native too.
  • Yield tells the currently executing thread to give a chance to the threads that have equal priority in the Thread Pool.
  • There is no guarantee that Yield will make the currently executing thread to runnable state immediately.
  • It can only make a thread from Ready State to Running State, not in wait or blocked state.
Example :
In below example program, I have created two threads named producer and consumer for no specific reason. Producer is set to minimum priority and consumer is set to maximum priority. I will run below code with/without commenting the line Thread.yield(). Without yield(), though the output changes sometimes, but usually first all consumer lines are printed and then all producer lines.
With using yield() method, both prints one line at a time and pass the chance to another thread, almost all the time.
1
package test.core.threads;
2
3
public class YieldExample
4
{
5
public static void main(String[] args)
6
{
7
Thread producer = new Producer();
8
Thread consumer = new Consumer();
9
10
producer.setPriority(Thread.MIN_PRIORITY); //Min Priority
11
consumer.setPriority(Thread.MAX_PRIORITY); //Max Priority
12
13
producer.start();
14
consumer.start();
15
}
16
}
17
18
class Producer extends Thread
19
{
20
public void run()
21
{
22
for (int i = 0; i < 5; i++)
23
{
24
System.out.println("I am Producer : Produced Item " + i);
25
Thread.yield();
26
}
27
}
28
}
29
30
class Consumer extends Thread
31
{
32
public void run()
33
{
34
for (int i = 0; i < 5; i++)
35
{
36
System.out.println("I am Consumer : Consumed Item " + i);
37
Thread.yield();
38
}
39
}
40
}
Copied!
Output of above program “without” yield() method
1
I am Consumer : Consumed Item 0
2
I am Consumer : Consumed Item 1
3
I am Consumer : Consumed Item 2
4
I am Consumer : Consumed Item 3
5
I am Consumer : Consumed Item 4
6
I am Producer : Produced Item 0
7
I am Producer : Produced Item 1
8
I am Producer : Produced Item 2
9
I am Producer : Produced Item 3
10
I am Producer : Produced Item 4
Copied!
Output of above program “with” yield() method added
1
I am Producer : Produced Item 0
2
I am Consumer : Consumed Item 0
3
I am Producer : Produced Item 1
4
I am Consumer : Consumed Item 1
5
I am Producer : Produced Item 2
6
I am Consumer : Consumed Item 2
7
I am Producer : Produced Item 3
8
I am Consumer : Consumed Item 3
9
I am Producer : Produced Item 4
10
I am Consumer : Consumed Item 4
Copied!

2) join()

java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join(); it causes the current thread to pause its execution until thread it join completes its execution. If there are multiple threads calling the join() methods that means overloading on join allows the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify. There are three overloaded join functions.
  1. 1.
    join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException. Syntax:
    1
    public final void join()
    Copied!
  2. 2.
    join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds). Syntax:
    1
    public final synchronized void join(long millis)
    Copied!
  3. 3.
    join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos). Syntax:
    1
    public final synchronized void join(long millis, int nanos)
    Copied!
    Example :
1
package com.gns.threads;
2
3
import java.util.Set;
4
5
public class TestYieldThread {
6
public static void main(String[] args) {
7
Thread producerThread = new Thread(new Producer(), "Producer-Thread");
8
Thread consumerThread = new Thread(new Consumer(), "Consumer-Thread");
9
producerThread.start();
10
consumerThread.start();
11
try {
12
producerThread.join();
13
} catch (InterruptedException e) {
14
// TODO Auto-generated catch block
15
e.printStackTrace();
16
}
17
System.out.println("main() execution resumed");
18
Set<Thread> threadsStates = Thread.getAllStackTraces().keySet();
19
for (Thread thread : threadsStates) {
20
System.out.println(thread + "state-> " + thread.getState());
21
}
22
}
23
}
Copied!
1
package com.gns.threads;
2
3
import java.util.Set;
4
5
public class Producer implements Runnable {
6
@Override
7
public void run() {
8
for (int i = 0; i < 5; i++) {
9
System.out.println("Producer producing item " + i);
10
}
11
Set<Thread> threadsStates = Thread.getAllStackTraces().keySet();
12
for (Thread thread : threadsStates) {
13
System.out.println(thread + "state-> " + thread.getState());
14
}
15
}
16
17
}
Copied!
1
package com.gns.threads;
2
3
public class Consumer implements Runnable {
4
@Override
5
public void run() {
6
for (int i = 0; i < 5; i++) {
7
System.out.println("Consumer consuming item " + i);
8
}
9
10
}
11
12
}
Copied!
1
Producer producing item 0
2
Consumer consuming item 0
3
Consumer consuming item 1
4
Consumer consuming item 2
5
Producer producing item 1
6
Consumer consuming item 3
7
Consumer consuming item 4
8
Producer producing item 2
9
Producer producing item 3
10
Producer producing item 4
11
Thread[Reference Handler,10,system]state-> WAITING
12
Thread[Attach Listener,5,system]state-> RUNNABLE
13
Thread[Producer-Thread,5,main]state-> RUNNABLE
14
Thread[main,5,main]state-> WAITING
15
Thread[Finalizer,8,system]state-> WAITING
16
Thread[Signal Dispatcher,9,system]state-> RUNNABLE
17
main() execution resumed
18
Thread[Reference Handler,10,system]state-> WAITING
19
Thread[Attach Listener,5,system]state-> RUNNABLE
20
Thread[main,5,main]state-> RUNNABLE
21
Thread[Finalizer,8,system]state-> WAITING
22
Thread[Signal Dispatcher,9,system]state-> RUNNABLE
Copied!
As we can see , main() thread was sent to waiting state when producerThread.join() was called.Hence after the completion of producerThread main() thread resumed its execution.

3) sleep()

This method causes the currently executing thread to sleep for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. Syntax:
1
// sleep for the specified number of milliseconds
2
public static void sleep(long millis) throws InterruptedException
3
4
//sleep for the specified number of milliseconds plus nano seconds
5
public static void sleep(long millis, int nanos)
6
throws InterruptedException
Copied!
1
// Java program to illustrate
2
// sleep() method in Java
3
import java.lang.*;
4
5
public class SleepDemo implements Runnable
6
{
7
Thread t;
8
public void run()
9
{
10
for (int i = 0; i < 4; i++)
11
{
12
System.out.println(Thread.currentThread().getName()
13
+ " " + i);
14
try
15
{
16
// thread to sleep for 1000 milliseconds
17
Thread.sleep(1000);
18
}
19
20
catch (Exception e)
21
{
22
System.out.println(e);
23
}
24
}
25
}
26
27
public static void main(String[] args) throws Exception
28
{
29
Thread t = new Thread(new SleepDemo());
30
31
// call run() function
32
t.start();
33
34
Thread t2 = new Thread(new SleepDemo());
35
36
// call run() function
37
t2.start();
38
}
39
}
Copied!
Output:
1
Thread-0 0
2
Thread-1 0
3
Thread-0 1
4
Thread-1 1
5
Thread-0 2
6
Thread-1 2
7
Thread-0 3
8
Thread-1 3
Copied!

Java Thread Sleep important points

  1. 1.
    It always pause the current thread execution.
  2. 2.
    The actual time thread sleeps before waking up and start execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time but for a busy system it will be little bit more.
  3. 3.
    Thread sleep doesn’t lose any monitors or locks current thread has acquired.
  4. 4.
    Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.

How Thread Sleep Works

Thread.sleep() interacts with the thread scheduler to put the current thread in wait state for specified period of time. Once the wait time is over, thread state is changed to runnable state and wait for the CPU for further execution. So the actual time that current thread sleep depends on the thread scheduler that is part of operating system.
Last modified 2yr ago
Copy link