j21
/*
- Write a java program to accept āNā Subject Names from a user store them into
LinkedList Collection and Display them by using Iterator interface.
*/
package com.mycompany.javaslip;
import java.util.*;
public class slip21_1
{
public static void main(String[] args) {
List<String> l = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("How many subjects:");
int n = sc.nextInt();
sc.nextLine();
System.out.println("Enter " + n + " subjects:");
for(int i=0; i<n; i++)
l.add(sc.nextLine());
System.out.println("Subjects are:");
Iterator itr = l.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
/*
Write a java program using Multithreading to solve producer consumer problem in
which a producer produces a value and consumer consume the value before producer
generate the next value. (Hint: use thread synchronization)
*/
package com.mycompany.javaslip;
import java.util.LinkedList;
class SharedResource {
private LinkedList<String> buffer = new LinkedList<>();
private int capacity = 1;
public synchronized void produce(String value) {
while(buffer.size() == capacity) {
try {
wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
buffer.add(value);
System.out.println("Produced: " + value);
notifyAll();
}
public synchronized String consume() {
while(buffer.size() == 0) {
try {
wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
String value = buffer.removeFirst();
System.out.println("Consume: " + value);
notifyAll();
return value;
}
}
class Producer extends Thread {
private SharedResource sharedResource;
public Producer(SharedResource sharedResource) {
this.sharedResource = sharedResource;
}
@Override
public void run() {
for(int i=0; i<5; i++) {
String value = "Value " + i;
sharedResource.produce(value);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread {
private SharedResource sharedResource;
public Consumer(SharedResource sharedResource) {
this.sharedResource = sharedResource;
}
@Override
public void run() {
for(int i=0; i<5; i++) {
String value = "Value " + i;
sharedResource.consume();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class slip21_2
{
public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
Producer producer = new Producer(sharedResource);
Consumer consumer = new Consumer(sharedResource);
producer.start();
consumer.start();
}
}