Open zhamri opened 6 years ago
class StarvationDemo extends Thread {
static int threadcount = 1;
public void run()
{
System.out.println(threadcount + "st " + " Thread is starts");
threadcount++;
}
public static void main(String[] args)
throws InterruptedException
{
StarvationDemo thread1 = new StarvationDemo();
thread1.setPriority(10);
thread1.start();
StarvationDemo thread2 = new StarvationDemo();
thread2.setPriority(9);
thread2.start();
}
}
Source Code
package rt_issues;
public class RT_Issues14 {
private double balance;
int id;
RT_Issues14(int id, double balance) {
this.id = id;
this.balance = balance;
}
synchronized double getBalance() {
// Wait to simulate io like database access ...
try {Thread.sleep(100l);} catch (InterruptedException e) {}
return balance;
}
synchronized void withdraw(double amount) {
balance -= amount;
}
synchronized void deposit(double amount) {
balance += amount;
}
synchronized void transfer(RT_Issues14 to, double amount) {
withdraw(amount);
to.deposit(amount);
}
public static void main(String[] args) {
final RT_Issues14 fooAccount = new RT_Issues14(1, 500d);
final RT_Issues14 barAccount = new RT_Issues14(2, 500d);
Thread balanceMonitorThread1 = new Thread(new BalanceMonitor(fooAccount), "BalanceMonitor");
Thread transactionThread1 = new Thread(new Transaction(fooAccount, barAccount, 250d), "Transaction-1");
Thread transactionThread2 = new Thread(new Transaction(fooAccount, barAccount, 250d), "Transaction-2");
balanceMonitorThread1.setPriority(Thread.MAX_PRIORITY);
transactionThread1.setPriority(Thread.MIN_PRIORITY);
transactionThread2.setPriority(Thread.MIN_PRIORITY);
// Start the monitor
balanceMonitorThread1.start();
// And later, transaction threads tries to execute.
try {Thread.sleep(100l);} catch (InterruptedException e) {}
transactionThread1.start();
transactionThread2.start();
}
}
class BalanceMonitor implements Runnable {
private RT_Issues14 account;
BalanceMonitor(RT_Issues14 account) { this.account = account;}
boolean alreadyNotified = false;
@Override
public void run() {
System.out.format("%s started execution%n", Thread.currentThread().getName());
while (true) {
if(account.getBalance() <= 0) {
// send email, or sms, clouds of smoke ...
break;
}
}
System.out.format("%s : account has gone too low, email sent, exiting.", Thread.currentThread().getName());
}
}
class Transaction implements Runnable {
private RT_Issues14 sourceAccount, destinationAccount;
private double amount;
Transaction(RT_Issues14 sourceAccount, RT_Issues14 destinationAccount, double amount) {
this.sourceAccount = sourceAccount;
this.destinationAccount = destinationAccount;
this.amount = amount;
}
public void run() {
System.out.format("%s started execution%n", Thread.currentThread().getName());
sourceAccount.transfer(destinationAccount, amount);
System.out.printf("%s completed execution%n", Thread.currentThread().getName());
}
}
Output
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package real_time;
/**
*
* @author master lab
*/
public class TrafficSignal_Starvation {
private String signal;
private String roadName;
private final static String GREEN = "Green";
private final static String RED = "Red";
public TrafficSignal_Starvation(String roadName, String signal) {
this.roadName = roadName;
this.signal = signal;
}
private static synchronized String whichLight(TrafficSignal_Starvation road) {
System.out.println("Show Signal of " + road.roadName + " - "
+ road.signal);
return road.signal;
}
private synchronized void green(String roadName) {
System.out.println(roadName + " - Switch on Green signal!");
this.signal = GREEN;
}
private synchronized void red(String roadName) {
System.out.println(roadName + " - Switch on Red signal!");
this.signal = RED;
}
public static synchronized void changeSignal(
TrafficSignal_Starvation road1, TrafficSignal_Starvation road2) {
road1.green(road1.roadName);
road2.red(road2.roadName);
}
public static void main(String[] args) {
final TrafficSignal_Starvation xRoad = new TrafficSignal_Starvation(
"X-Road", GREEN);
final TrafficSignal_Starvation yRoad = new TrafficSignal_Starvation(
"Y-Road", RED);
Thread whichSignalThread = new Thread() {
public void run() {
while (xRoad.signal.equals(GREEN)) {
TrafficSignal_Starvation.whichLight(xRoad);
}
}
};
Thread thread1 = new Thread() {
public void run() {
TrafficSignal_Starvation.changeSignal(xRoad, yRoad);
}
};
Thread thread2 = new Thread() {
public void run() {
TrafficSignal_Starvation.changeSignal(yRoad, xRoad);
}
};
whichSignalThread.setPriority(Thread.MAX_PRIORITY);
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
whichSignalThread.start();
thread1.start();
thread2.start();
}
}
https://www.vikastechblog.com/java/multithreading/deadlock-livelock-starvation.html
Source Code
/**
*
*
*
*/
class Display implements Runnable{
private exercise12 td;
Display(exercise12 td){
this.td = td;
}
@Override
public void run() {
td.displayValues();
System.out.println("Calling again");
td.displayValues();
System.out.println("Calling again");
td.displayValues();
//System.out.println("Calling again");
}
}
/**
*
*
*
*/
class Display1 implements Runnable{
private exercise12 td;
Display1(exercise12 td){
this.td = td;
}
@Override
public void run() {
try {
// introducing some delay
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
td.displayValues();
//System.out.println("Calling again");
}
}
public class exercise12 {
synchronized void displayValues(){
System.out.println("In ThreadStarveDemo For thread " +
Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("For thread " + Thread.currentThread().getName());
for(int i = 0; i < 3; i++){
System.out.println("Value of i " + i);
}
}
public static void main(String[] args) {
exercise12 td1 = new exercise12();
// Creating 3 threads
Thread thread0 = new Thread(new Display1(td1));
Thread thread1 = new Thread(new Display(td1));
Thread thread2 = new Thread(new Display(td1));
// Setting priorities
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread0.setPriority(Thread.MIN_PRIORITY);
thread0.start();
thread1.start();
thread2.start();
}
}
Results
Main class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package starvation;
/**
*
* @author master lab
*/
public class Starvation {
public static void main(String[] args) {
Worker worker = new Worker();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
worker.work();
}
}).start();
}
}
}
Worker class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package starvation;
import java.io.*;
/**
* Worker.java
* This class is used to demonstrate starvation situation.
* @author www.codejava.net
*/
public class Worker {
public synchronized void work() {
String name = Thread.currentThread().getName();
String fileName = name + ".txt";
try (
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
) {
writer.write("Thread " + name + " wrote this mesasge");
} catch (IOException ex) {
ex.printStackTrace();
}
while (true) {
System.out.println(name + " is working");
}
}
}
Output
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author master lab
*/
import java.util.concurrent.atomic.AtomicInteger;
public class Starvation {
private static Object mutex = new Object();
private static volatile boolean isActive = true;
public static void main(String[] args) {
Thread t1 = new Thread(new Worker(), "Thread_1_P10");
Thread t2 = new Thread(new Worker(), "Thread_2_P8");
// Priorities only serve as hints to scheduler, it is up to OS implementation to decide
t1.setPriority(10);
t2.setPriority(8);
t1.start();
t2.start();
// Make the Main Thread sleep for 5 seconds
// then set isActive to false to stop all threads
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isActive = false;
}
private static class Worker implements Runnable {
private AtomicInteger runCount = new AtomicInteger();
public void run() {
// tight loop using volatile variable as active flag for proper shutdown
while (isActive) {
synchronized (mutex) {
try {
doWork();
} catch (Exception e) {
System.out.format("%s was interrupted...\n", Thread.currentThread().getName());
e.printStackTrace();
}
}
}
System.out.format("DONE===> %s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.get());
}
private void doWork() {
System.out.format("%s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.getAndIncrement());
}
}
}
Output
References https://avaldes.com/java-thread-starvation-livelock-with-examples/
Starvation
package issue_14;
public class StarvationDemo extends Thread{
static int threadcount = 1;
public void run()
{
System.out.println(threadcount + "st Child" +
" Thread execution starts");
System.out.println("Child thread execution completes");
threadcount++;
}
public static void main(String[] args)
throws InterruptedException
{
System.out.println("Main thread execution starts");
// Thread priorities are set in a way that thread5
// gets least priority.
StarvationDemo thread1 = new StarvationDemo();
thread1.setPriority(10);
StarvationDemo thread2 = new StarvationDemo();
thread2.setPriority(9);
StarvationDemo thread3 = new StarvationDemo();
thread1.setPriority(8);
StarvationDemo thread4 = new StarvationDemo();
thread1.setPriority(7);
StarvationDemo thread5 = new StarvationDemo();
thread1.setPriority(6);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
// Here thread5 have to wait beacause of the
// other thread. But after waiting for some
// interval, thread5 will get the chance of
// execution. It is known as Starvation
thread5.start();
System.out.println("Main thread execution completes");
}
}
Output
Reference : https://www.geeksforgeeks.org/deadlock-starvation-java/
package issue14.starvation;
import java.util.concurrent.atomic.AtomicInteger;
public class Issue14Starvation {
private static Object mutex = new Object();
private static volatile boolean isActive = true;
public static void main(String[] args) {
Thread t1 = new Thread(new Worker(), "Thread_1_P10");
Thread t2 = new Thread(new Worker(), "Thread_2_P8");
// Priorities only serve as hints to scheduler, it is up to OS implementation to decide
t1.setPriority(10);
t2.setPriority(8);
t1.start();
t2.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isActive = false;
}
private static class Worker implements Runnable {
private AtomicInteger runCount = new AtomicInteger();
public void run() {
// tight loop using volatile variable as active flag for proper shutdown
while (isActive) {
synchronized (mutex) {
try {
doWork();
} catch (Exception e) {
System.out.format("%s was interrupted...\n", Thread.currentThread().getName());
e.printStackTrace();
}
}
}
System.out.format("DONE===> %s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.get());
}
private void doWork() {
System.out.format("%s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.getAndIncrement());
}
}
}
public class issue13 {
private String signal;
private String roadName;
private final static String GREEN = "Green";
private final static String RED = "Red";
public issue13(String roadName, String signal) {
this.roadName = roadName;
this.signal = signal;
}
private static synchronized String whichLight(issue13 road) {
System.out.println("Show Signal of " + road.roadName + " - "
+ road.signal);
return road.signal;
}
private synchronized void green(String roadName) {
System.out.println(roadName + " - Switch on Green signal!");
this.signal = GREEN;
}
private synchronized void red(String roadName) {
System.out.println(roadName + " - Switch on Red signal!");
this.signal = RED;
}
public static synchronized void changeSignal(
issue13 road1, issue13 road2) {
road1.green(road1.roadName);
road2.red(road2.roadName);
}
public static void main(String[] args) {
final issue13 xRoad = new issue13(
"X-Road", GREEN);
final issue13 yRoad = new issue13(
"Y-Road", RED);
Thread whichSignalThread = new Thread() {
public void run() {
while (xRoad.signal.equals(GREEN)) {
issue13.whichLight(xRoad);
}
}
};
Thread thread1 = new Thread() {
public void run() {
issue13.changeSignal(xRoad, yRoad);
}
};
Thread thread2 = new Thread() {
public void run() {
issue13.changeSignal(yRoad, xRoad);
}
};
whichSignalThread.setPriority(Thread.MAX_PRIORITY);
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
whichSignalThread.start();
thread1.start();
thread2.start();
}
}
CODE
package starvation;
class Starvation extends Thread {
static int threadcount = 1;
public void run()
{
System.out.println(threadcount + "st Child" +
" Thread execution starts");
System.out.println("Child thread execution completes");
threadcount++;
}
public static void main(String[] args)
throws InterruptedException
{
Starvation thread1 = new Starvation();
thread1.setPriority(10);
Starvation thread2 = new Starvation();
thread2.setPriority(9);
thread1.start();
thread2.start();
}
}
OUTPUT
REFERENCE
https://www.geeksforgeeks.org/deadlock-starvation-java/
package exercise13;
public class Exercise13 extends Thread {
static int threadcount = 1;
public void run()
{
System.out.println(threadcount + "st Child" +
" Thread execution starts");
System.out.println("Child thread execution completes");
threadcount++;
}
public static void main(String[] args)
throws InterruptedException
{
System.out.println("Main thread execution starts");
// Thread priorities are set in a way that thread5
// gets least priority.
Exercise13 thread1 = new Exercise13();
thread1.setPriority(10);
Exercise13 thread2 = new Exercise13();
thread2.setPriority(9);
Exercise13 thread3 = new Exercise13();
thread1.setPriority(8);
Exercise13 thread4 = new Exercise13();
thread1.setPriority(7);
Exercise13 thread5 = new Exercise13();
thread1.setPriority(6);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
System.out.println("Main thread execution completes");
}
}
Output
package stiw3054_13;
/*
public class ThreadStarvationExample { private static Object mutex = new Object(); private static volatile boolean isActive = true;
public static void main(String[] args) { Thread t1 = new Thread(new Worker(), "Thread_1_P10"); Thread t2 = new Thread(new Worker(), "Thread_2_P8"); //Thread t3 = new Thread(new Worker(), "Thread_3_P6"); //Thread t4 = new Thread(new Worker(), "Thread_4_P4"); //Thread t5 = new Thread(new Worker(), "Thread_5_P2");
// Priorities only serve as hints to scheduler, it is up to OS implementation to decide
t1.setPriority(10);
t2.setPriority(8);
//t3.setPriority(6);
//t4.setPriority(4);
//t5.setPriority(2);
t1.start();
t2.start();
//t3.start();
//t4.start();
//t5.start();
// Make the Main Thread sleep for 5 seconds
// then set isActive to false to stop all threads
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isActive = false;
}
private static class Worker implements Runnable { private AtomicInteger runCount = new AtomicInteger();
public void run() {
// tight loop using volatile variable as active flag for proper shutdown
while (isActive) {
synchronized (mutex) {
try {
doWork();
} catch (Exception e) {
System.out.format("%s was interrupted...\n", Thread.currentThread().getName());
e.printStackTrace();
}
}
}
System.out.format("DONE===> %s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.get());
}
private void doWork() {
System.out.format("%s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.getAndIncrement());
}
} }
package com.mycompany.starvation;
import java.util.concurrent.atomic.AtomicInteger;
public class starvationExample {
private static Object mutex = new Object();
private static volatile boolean isActive = true;
public static void main(String[] args) {
Thread t1 = new Thread(new Worker(), "Thread_1_Nurul");
Thread t2 = new Thread(new Worker(), "Thread_2_Basitah");
// Priorities only serve as hints to scheduler, it is up to OS implementation to decide
t1.setPriority(10);
t2.setPriority(8);
t1.start();
t2.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isActive = false;
}
private static class Worker implements Runnable {
private AtomicInteger runCount = new AtomicInteger();
public void run() {
// tight loop using volatile variable as active flag for proper shutdown
while (isActive) {
synchronized (mutex) {
try {
doWork();
} catch (Exception e) {
System.out.format("%s was interrupted...\n", Thread.currentThread().getName());
e.printStackTrace();
}
}
}
System.out.format("DONE===> %s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.get());
}
private void doWork() {
System.out.format("%s: Current runCount is %d...\n", Thread.currentThread().getName(), runCount.getAndIncrement());
}
}
}
Reference 1.https://avaldes.com/java-thread-starvation-livelock-with-examples/
package starvation;
/**
*
* @author esp
*/
class Starvation extends Thread {
static int threadcount = 1;
public void run()
{
System.out.println(threadcount + "st Child" +
" Thread execution starts");
System.out.println("Child thread execution completes");
threadcount++;
}
public static void main(String[] args)
throws InterruptedException
{
System.out.println("Main thread execution starts");
// Thread priorities are set in a way that thread5
// gets least priority.
Starvation thread1 = new Starvation();
thread1.setPriority(10);
Starvation thread2 = new Starvation();
thread2.setPriority(9);
Starvation thread3 = new Starvation();
thread1.setPriority(8);
Starvation thread4 = new Starvation();
thread1.setPriority(7);
Starvation thread5 = new Starvation();
thread1.setPriority(6);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
// Here thread5 have to wait beacause of the
// other thread. But after waiting for some
// interval, thread5 will get the chance of
// execution. It is known as Starvation
thread5.start();
System.out.println("Main thread execution finish");
}
}
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* @author USER
*/
public class starvation {
private double balance;
int id;
starvation(int id, double balance) {
this.id = id;
this.balance = balance;
}
synchronized double getBalance() {
// Wait to simulate io like database access ...
try {Thread.sleep(100l);} catch (InterruptedException e) {}
return balance;
}
synchronized void withdraw(double amount) {
balance -= amount;
}
synchronized void deposit(double amount) {
balance += amount;
}
synchronized void transfer(starvation to, double amount) {
withdraw(amount);
to.deposit(amount);
}
public static void main(String[] args) {
final starvation fooAccount = new starvation(1, 500d);
final starvation barAccount = new starvation(2, 500d);
Thread balanceMonitorThread1 = new Thread(new BalanceMonitor(fooAccount), "BalanceMonitor");
Thread transactionThread1 = new Thread(new Transaction(fooAccount, barAccount, 250d), "Transaction-1");
Thread transactionThread2 = new Thread(new Transaction(fooAccount, barAccount, 250d), "Transaction-2");
balanceMonitorThread1.setPriority(Thread.MAX_PRIORITY);
transactionThread1.setPriority(Thread.MIN_PRIORITY);
transactionThread2.setPriority(Thread.MIN_PRIORITY);
// Start the monitor
balanceMonitorThread1.start();
// And later, transaction threads tries to execute.
try {Thread.sleep(100l);} catch (InterruptedException e) {}
transactionThread1.start();
transactionThread2.start();
}
}
class BalanceMonitor implements Runnable {
private starvation account;
BalanceMonitor( starvation account) { this.account = account;}
boolean alreadyNotified = false;
@Override
public void run() {
System.out.format("%s started execution%n", Thread.currentThread().getName());
while (true) {
if(account.getBalance() <= 0) {
// send email, or sms, clouds of smoke ...
break;
}
}
System.out.format("%s : account has gone too low, email sent, exiting.", Thread.currentThread().getName());
}
}
class Transaction implements Runnable {
private starvation sourceAccount, destinationAccount;
private double amount;
Transaction( starvation sourceAccount, starvation destinationAccount, double amount) {
this.sourceAccount = sourceAccount;
this.destinationAccount = destinationAccount;
this.amount = amount;
}
public void run() {
System.out.format("%s started execution%n", Thread.currentThread().getName());
sourceAccount.transfer(destinationAccount, amount);
System.out.printf("%s completed execution%n", Thread.currentThread().getName());
}
}
https://richardbarabe.wordpress.com/2014/02/21/java-deadlock-livelock-and-lock-starvation-examples/
Java code
public class Starvation 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 Starvation(resource, String.valueOf(i), fair))).start();
}
// suspend main thread
synchronized (Starvation.class) {
try {
Starvation.class.wait();
} catch (InterruptedException ignored) {
}
}
}
public Starvation(Object resource, String message, boolean fair)
{
this.resource = resource;
this.message = message;
this.fair = fair;
}
public void run()
{
synchronized (this) {
for (;;) {
synchronized (resource) {
print(message);
try {
(fair ? resource : this).wait(100);
} catch (InterruptedException ignored) {
}
}
}
}
}
private static void print(String str)
{
synchronized (System.out) {
System.out.print(str);
System.out.flush();
}
}
}
Output
References
package com.mycompany.issue14;
/**
*
* @author Alif Haikal
*/
class Issue14 extends Thread {
static int threadcount = 1;
public void run()
{
System.out.println(threadcount + "st Child" +
" Thread execution starts");
System.out.println("Child thread execution completes");
threadcount++;
}
public static void main(String[] args)
throws InterruptedException
{
System.out.println("Main thread execution starts");
// Thread priorities are set in a way that thread5
// gets least priority.
Issue14 thread1 = new Issue14();
thread1.setPriority(10);
Issue14 thread2 = new Issue14();
thread2.setPriority(9);
Issue14 thread3 = new Issue14();
thread1.setPriority(8);
Issue14 thread4 = new Issue14();
thread1.setPriority(7);
Issue14 thread5 = new Issue14();
thread1.setPriority(6);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
System.out.println("Main thread execution completes");
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package issues;
import java.io.IOException;
/**
*
* @author abdullah
*/
public class Issues14 {
public static void main(String[] args) {
ParrallelThread p = new ParrallelThread();
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
public void run() {
p.go();
}
}).start();
}
}
}
class ParrallelThread {
public synchronized void go() {
String threadname = Thread.currentThread().getName();
int threadcount = 0;
try {
System.out.println ("Thread Name :" + threadname );
} catch (Exception ex) {
System.out.println("OOPS!!");
}
while (true) {
System.out.println(threadname + " is running");
++threadcount;
System.out.println("Thread " + threadname + " has counted " + threadcount);
// try {
// wait(1000);
// } catch (InterruptedException ex) {
// ex.printStackTrace();
// }
}
}
}
This program is suppose to start 5 threads and run them fairly but only the first thread gets created, other threads are unable to execute the go() method because while loop runs forever so that the first executed thread never release the lock, causing other threads to wait forever hereby causing starvation. Simple solution will be to uncomment the following line of code
try {
wait(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
RESULT DURING STARVATION :
AFTER SOLVING THE STARVATION :
Write a Java program using TWO (2) threads to simulate Starvation.