Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using Java make a console based program that will create two threds, one produce

ID: 3855047 • Letter: U

Question

Using Java make a console based program that will create two threds, one producer one consumer. producer must open input file and copy values into a circular bufer. Consumer must open an output file and repetedly copy values from the same circular buffer. Both use a random number of bytes betwen 1 and including n taht must be copied each iteration. n is set each time by the user. if producer unable to write to the buffer because it is full or if consumer is unable to read from buffer because not enough unead items, then it should go to following iteration. Only exception is when producer has read entire file, then consumer does not have to continue generatin random numbers until it gets an exact hit, instead it must write the rest of the buffer to complete copy. When done running the output should be the same as input file.

Explanation / Answer

The required code for the Producer Consumer problem is as follows:

PCTesting.java

public class PCTesting {
public static void main(String[] args) {
Holes ch = new Holes();
Prod prod = new Prod(ch, 1);
Cons cons = new Cons(ch, 1);
prod.start();
cons.start();
}
}

Holes.java

class Holes {
private int cont;
private boolean ready = false;

public synchronized int get() {
while (ready == false) {
try {
wait();
} catch (InterruptedException e) {}
}
ready = false;
notifyAll();
return cont;
}
public synchronized void insert(int val) {
while (ready == true) {
try {
wait();
} catch (InterruptedException e) { }
}
cont = val;
ready = true;
notifyAll();
}
}

Cons.java
class Cons extends Thread {
private Holes hole;
private int no;

public Cons(Holes ch, int no) {
hole = ch;
this.no = no;
}
public void run() {
int val = 0;
for (int uu = 0; uu < 10; uu++) {
val = hole.get();
System.out.println("Cons #" + this.no + " got: " + val);
}
}
}

Prod.java
class Prod extends Thread {
private Holes hole;
private int no;
public Prod(Holes ch, int no) {
hole = ch;
this.no = no;
}
public void run() {
for (int uu = 0; uu < 10; uu++) {
hole.insert(uu);
System.out.println("Prod #" + this.no + " insert: " + uu);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

Hence, this is the code for the given Producer COnsumer problem using multithread and the random numbers between 1-100.

Please rate the answer if it helped.....Thankyou

Hope it helps.....

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote