Tutorialspoint examples

Learn java tutorial with examples for beginners online

Starvation in java


Starvation is a situation when a thread is in waiting state from long period because it not getting access of shared resources or because higher priority threads are coming.



 * This program is used to show the starvation problem. 
 * @author javawithease
public class StarvationExample implements Runnable{
	private final Object resource;
	private final String message;
	private final boolean fair;
	public static void main(String[] args)
		boolean fair = false;
		if (args != null && args.length >= 1 && args[0].equals("fair")) {
			fair = true;
		// get the number of available CPUs, do twice as much threads.
		final int cpus = Runtime.getRuntime().availableProcessors();
		System.out.println("" + cpus + " available CPUs found");
		final int runners = cpus * 2;
		System.out.println("starting " + runners + " runners");
		final Object resource = new Object();
		// create sample runners and start them
		for (int i = 1; i <= runners; i++) {
			(new Thread(new StarvationExample(resource, String.valueOf(i), fair))).start();
		// suspend main thread
		synchronized (StarvationExample.class) {
			try {
			} catch (InterruptedException ignored) {
	public StarvationExample(Object resource, String message, boolean fair)
		this.resource = resource;
		this.message = message;
		this.fair = fair;
	public void run()
		synchronized (this) {
			for (;;) {
				synchronized (resource) {
					try {
						(fair ? resource : this).wait(100);
					} catch (InterruptedException ignored) {
	private static void print(String str)
		synchronized (System.out) {


4 available CPUs found
starting 8 runners

Download this example.
Next Topic: Inter-thread communication in java with example.
Previous Topic: Deadlock in java with example.

Related Topics:

Multithreading in java.
Thread life cycle in java.
Way of creating thread in java.
Commonly used methods of Thread class.
Thread scheduling in java with example.
Thread priority in java with example.
Naming a thread in java with example.
Joining a thread in java with example.
Daemon thread in java with example.
Can we start a thread twice?
Can we call run method directly?
Difference between Thread.yield() and Thread.sleep() methods.
Deadlock in java with example.
Starvation in java with example.
Inter-thread communication in java with example.
Synchronization in java with example.
Synchronized method in java with example.
Static synchronization in java with example.
Synchronized block in java with example.


Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status