Starvation describes a situation where a greedy thread holds a resource for a long time so other threads are blocked forever. If you write a program in which several concurrent threads are competing for resources, you must take precautions to ensure fairness.
Thread starvation in multi-threading may happen because other “greedy” threads are gaining the lock and access to the shared resource, resulting in a thread (or a bunch of threads) getting starved of access to shared resources and CPU time.
Sample Program:
import java.io.BufferedWriter;
import java.io.FileWriter;
class StarvationTask {
public synchronized void filePrint(String helloMessage) {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Sankesh\\Desktop\\architect\\a.txt"));
while(true) {
System.out.println("Hello i m writting in File"+Thread.currentThread().getName());
bufferedWriter.write(helloMessage);
}
} catch (Exception e) {
e.printStackTrace();
}}
}
public class StarvationDemo {
public static void main(String[] args) {
System.out.println("Starvation Demo");
StarvationTask starvationTask = new StarvationTask();
for(int i=0;i<=9;i++) {
new Thread(
new Runnable() {
@Override
public void run() { starvationTask.filePrint("hello i m writting in File"+Thread.currentThread().getName());
}
}
).start();
}}}
Sample Output:
Thread starvation in multi-threading may happen because other “greedy” threads are gaining the lock and access to the shared resource, resulting in a thread (or a bunch of threads) getting starved of access to shared resources and CPU time.
Sample Program:
import java.io.BufferedWriter;
import java.io.FileWriter;
class StarvationTask {
public synchronized void filePrint(String helloMessage) {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Sankesh\\Desktop\\architect\\a.txt"));
while(true) {
System.out.println("Hello i m writting in File"+Thread.currentThread().getName());
bufferedWriter.write(helloMessage);
}
} catch (Exception e) {
e.printStackTrace();
}}
}
public class StarvationDemo {
public static void main(String[] args) {
System.out.println("Starvation Demo");
StarvationTask starvationTask = new StarvationTask();
for(int i=0;i<=9;i++) {
new Thread(
new Runnable() {
@Override
public void run() { starvationTask.filePrint("hello i m writting in File"+Thread.currentThread().getName());
}
}
).start();
}}}
Sample Output:
No comments:
Post a Comment