I try to develep simulates a bank branch.I want to generate a new customer and add the customer to the queue(or ArrayList). If there are available tellers (there are 2 tellers), remove customer from the list and assign them to tellers. I used 2 threads, first one is generate customer and add to the list. Second one is belongs to tellers. I have some problem.
Customer class
public class Customer {
private int customerID;
private int processTime;
ArrayList<Integer> customerIDList = new ArrayList<>();
ArrayList<Integer> processTimeList = new ArrayList<>();
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public int getProcessTime() {
return processTime;
}
public void setProcessTime(int processTime) {
this.processTime = processTime;
}
public ArrayList<Integer> getCustomerIDList() {
return customerIDList;
}
public void setCustomerIDList(ArrayList<Integer> customerIDList) {
this.customerIDList = customerIDList;
}
public ArrayList<Integer> getProcessTimeList() {
return processTimeList;
}
public void setProcessTimeList(ArrayList<Integer> processTimeList) {
this.processTimeList = processTimeList;
}
}
Teller class
public class Teller {
private boolean status = true;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
CustomerThread class
public class CustomerThread extends Thread {
Customer c = new Customer();
Methods method = new Methods();
#Override
public void run() {
for(int i = 0; i < 10; i++) {
try {
c.getCustomerIDList().add(i+1);
c.getProcessTimeList().add(method.generateProcessTime());
System.out.println("ID : " + c.getCustomerIDList().get(i) + " - Process Time : " + c.getProcessTimeList().get(i));
Thread.sleep(100);
}
catch (InterruptedException ex) {
Logger.getLogger(CustomerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Between to customers 100 msec
TellerThread class
public class TellerThread extends Thread{
Customer c1 = new Customer();
Teller teller1 = new Teller();
Teller teller2 = new Teller();
#Override
public void run() {
try {
Thread.sleep(100);
while(c1.getProcessTimeList().isEmpty()) {
if(teller1.isStatus()) {
teller1.setStatus(false);
System.out.println("Customer " + c1.getCustomerIDList().get(0) + " came teller1.");
c1.getCustomerIDList().remove(0);
Thread.sleep(c1.getProcessTimeList().get(0));
System.out.println("Teller 1 is waiting of " + c1.getProcessTimeList().get(0) + " msec.");
c1.getProcessTimeList().remove(0);
teller1.setStatus(true);
System.out.println("Teller 1 is Available.");
}
else if(teller2.isStatus()) {
teller2.setStatus(false);
System.out.println("Customer " + c1.getCustomerIDList().get(0) + " came teller2.");
c1.getCustomerIDList().remove(0);
Thread.sleep(c1.getProcessTimeList().get(0));
System.out.println("Teller 2 is waiting of " + c1.getProcessTimeList().get(0) + " msec.");
c1.getProcessTimeList().remove(0);
teller2.setStatus(true);
System.out.println("Teller 2 is Available");
}
else {
System.out.println("There is no customer..");
}
}
} catch (InterruptedException ex) {
Logger.getLogger(TellerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and Test class
public class Test {
public static void main(String[] args) {
CustomerThread ct = new CustomerThread();
TellerThread tt = new TellerThread();
ExecutorService es = Executors.newCachedThreadPool();
es.execute(ct);
es.execute(tt);
es.shutdown();
}
}
When I execute this codes, I see only customers on the output. There are no tellers process. How can I fix this?
Related
-----ATM.java-----
public class ATM {
int cash;
boolean inService;
public ATM() {
cash = 0;
inService = false;
}
public ATM(int x, boolean y) {
cash = x;
inService = y;
}
public int queryCash() {
return cash;
}
public void increaseCash(int x) {
cash = cash + x;
}
public void reduceCash(int x) {
cash = cash - x;
}
public boolean getServiceStatus() {
return inService;
}
public void changeServiceStatus() {
if (inService) {
inService = false;
System.out.println("inService is now false");
}
else {
System.out.println("inService is now true");
}
}
public class CashDispenser {
public void dispenseCash(int x) {
reduceCash(x);
System.out.println(x + " dollars has been dispensed.");
}
}
CashDispenser dispenser = new CashDispenser();
public class ReceiptPrinter {
public void printReceipt() {
System.out.println("Receipt has been printed.");
}
}
ReceiptPrinter printer = new ReceiptPrinter();
public class CardReader{
public void readCard() {
System.out.println("Card has been read.");
}
}
CardReader reader = new CardReader();
public class KeypadDisplay{
public void displayPINverification() {
System.out.println("PIN has been verified.");
}
}
KeypadDisplay display = new KeypadDisplay();
}
------Person.java-------
public class Person {
String name;
public Person(){
name = "default";
}
public String getName() {
return name;
}
public void setName(String nameString) {
name = nameString;
System.out.println("The name is set to "+ name);
}
}
--------Operator.java------
public class Operator extends Person {
public void topUpATM(ATM atm) {
System.out.println("Current inService is "+ atm.inService);
System.out.println("Current cash is "+ atm.cash);
if (atm.getServiceStatus() == true){
atm.changeServiceStatus();
System.out.println("ATM now has "+ atm.queryCash()+" dollars.");
atm.changeServiceStatus();
}
if (atm.queryCash() < 5000){
atm.increaseCash(5000);
System.out.println("ATM now" + atm.queryCash()+ " dollars.");
atm.changeServiceStatus();
}
}
}
---------Customer.java-------- **I dont know what am i doing wrong over here as this is the place where getserviceStatus() should return true but it is returning false. Other functions work perfectly so far but I am stuck on this issue for quite a while now and I cannot figure it out why is it that way. **
public class Customer extends Person {
public void withdrawCash(ATM atm, int amount) {
//atm.changeServiceStatus();
System.out.println("Current inService is "+atm.getServiceStatus());
if (!atm.getServiceStatus()) {
System.out.println("ATM is not in service.");
}
else if (atm.queryCash()<amount) {
System.out.println("ATM has insufficient cash");
}
else {
atm.reader.readCard();
atm.display.displayPINverification();
atm.dispenser.dispenseCash(amount);
atm.printer.printReceipt();
System.out.println(amount+" successfully withdrawn from ATM");
}
}
}
----------------A00.java------------
import java.util.Scanner;
public class A00 {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
int Number;
System.out.println("Please enter between 0 and 10,000");
Number = input.nextInt();
ATM atm_1 = new ATM (0,false);
ATM atm_2 = new ATM (Number,true);
input.nextLine();
System.out.println("Please enter a name for the operator");
String name = input.nextLine();
Operator operate = new Operator();
operate.setName(name);
System.out.println("Processing ATM 1");
operate.topUpATM(atm_1);
System.out.println("Processing ATM 2");
operate.topUpATM(atm_2);
Customer cust = new Customer();
String customer;
System.out.println("Enter the name of a customer:");
customer = input.nextLine();
cust.setName(customer);
System.out.println("Please enter the amount you want to withdraw: ");
int withdraw;
withdraw = input.nextInt();
cust.withdrawCash(atm_1, withdraw);
input.close();
}
}
You recall the method withdrawCash passing atm_1 as parameter and atm_1 is istantiated as ATM atm_1 = new ATM (0,false);
The second parameter in ATM constructor sets inService = false
So, I'm working on a project with a loop (while (true) { //do stuff) and I have values stored in a map (only 2 entries).
First issue: Methods are executing twice (I think it is an issue in the map portion). The VirtualPet.tick and the VirtualPet.feed method is being executed twice per loop.
Second issue: map.get(key) is executing on all keys, not just specified key.
In my main class:
private static VirtualPetShelter shelter = new VirtualPetShelter();
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
generatePets();
gameLoop();
}
private static void showPets() {
shelter.showPets();
}
private static void generatePets() {
VirtualPet pet1 = new VirtualPet();
VirtualPet pet2 = new VirtualPet();
shelter.addPet("Max", pet1);
shelter.addPet("Skippy", pet1);
}
private static void gameLoop() {
while (true) {
whatToDo();
shelter.tick();
showPets();
}
}
private static void whatToDo() {
System.out.println("What would you like to do?");
System.out.println("\t 1: Feed");
int response = input.nextInt();
input.nextLine();
switch (response) {
case 1:
feedOptions();
break;
}
}
private static void feedOptions() {
System.out.println("Enter pet name or \"all\" to feed all:");
showPetNames();
String response = input.nextLine();
if (response.toLowerCase().equals("all")) {
shelter.feedAllPets();
} else {
shelter.feedPet(response);
}
}
In my Shelter class:
private Map<String, VirtualPet> pets = new HashMap<>();
public VirtualPetShelter() {
}
public void addPet(String name, VirtualPet pet) {
pets.put(name, pet);
}
public void showPets() {
for (Map.Entry<String, VirtualPet> entry : pets.entrySet())
System.out.println("\t" + entry.getKey() + "\n" +
"\t\tHunger: " + entry.getValue().getHunger());
}
public void showPetNames() {
for (Map.Entry<String, VirtualPet> entry : pets.entrySet())
System.out.println(entry.getKey());
}
public void feedAllPets() {
for (VirtualPet value : pets.values())
value.feed();
}
public void feedPet(String name) {
pets.get(name).feed();
}
public void tick() {
for (VirtualPet value : pets.values())
value.tick();
}
In VirtualPet class:
private int hunger;
public VirtualPet() {
hunger = 5;
}
public int getHunger() {
return hunger;
}
public void feed() {
hunger -= 2;
}
public void tick(){
hunger += 1;
}
How do you call the parents constructor and give the parent constructor a parameter of 50? I need to make a constructor for HoldenDB which as no formal parameter and calls its parents constructor.
I have started by extending HoldeDB to VechicleDB, however, I'm unsure how to proceed for there.
If someone could help me that would be much appreciated.
import java.util.ArrayList;
class Vehicle {
int capacity;
String make;
void setCapacity(int setCapacity) {
this.capacity = setCapacity;
System.out.println("New Capacity = " + setCapacity);
}
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
}
#Override
public void print() {
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
#Override
public void setCapacity(int setCapacity) {
System.out.println("Cannot change capacity of a car");
}
}
class VehicleDB {
ArrayList<Vehicle> db = new ArrayList<Vehicle>();
void addVehicle(Vehicle c){
db.add(c);
}
void print(){
System.out.println("=== Vehicle Data Base ===");
for(Vehicle v: db){
v.print();
}
}
}
class HoldenDB extends VehicleDB {
void addCar(Vehicle c){
db.add(c);
}
}
class Task5 {
public static void main (String[]args){
HoldenDB db = new HoldenDB ();
db.addCar(1200,"sedan","Barina");
db.addCar(3800,"wagon","Commodore");
db.print();
}
}
public class VehicleDB {
private int n;
public VehicleDB(int n) {
this.n = n;
}
}
public class HoldenDB extends VehicleDB {
public HoldenDB() {
super(50);
}
}
I need help removing a specific object from an arraylist. I'm creating objects with a unique ID and grade for each object.I'm trying to use this unique ID to remove an object from the arraylist, but am having trouble figuring out why my code isn't working. I have my main Driver class, a superclass, and a subclass.
The subclass is where the object information is passed from and extends the superclass. I thought that since the subclass is extended, it would be able to be defined from there.
The problem that is occurring is line 49 of the superclasss. Eclipse says that getStudentID isn't defined in the class.
I am trying to modify code that my instructor provided in order to locate this unique ID that an object in the arraylist has. I believe I did everything correctly, but the method "locationPerson" doesn't seem to see the getStudentID() method in the subclass.
Here is the code. Any help would be appreciated!
Subclass
public class StudentEnrollee extends ClassSection{
private int grade;
private String studentID;
StudentEnrollee() {
setStudentID("000-000");
setGrade(0);
}
StudentEnrollee(String ID, int theGrade) {
setStudentID(ID);
setGrade(0);
}
//STUDENT ID
public String getStudentID() {
return studentID;
}
public void setStudentID(String theStudentID) {
this.studentID = theStudentID;
}
//STUDENT GRADE
public int getGrade() {
return grade;
}
public void setGrade(int studentGrade) {
this.grade = studentGrade;
}
public String toString() {
return("Student ID : " + studentID + "\n" +
"Student Grade: " + grade);
}
}
Superclass
import java.util.ArrayList;
import java.util.List;
public class ClassSection {
private int crn, courseNumber, capacity, enrollment, ID, student;
private String departmentCode, courseMode, meetingDay, meetingTime;
//CONSTRUCTOR
ClassSection() {
setCrn(0);
setDepartmentCode("");
setCourseNumber(0);
setCourseMode("");
setMeetingDay("");
setMeetingTime("");
setCapacity(0);
setEnrollment(0);
setID(0);
}
ClassSection(int crn, String departmentCode, int courseNumber, String courseMode, String meetingDay, String meetingTime, int capacity, int enrollment, int ID) {
setCrn(crn);
setDepartmentCode(departmentCode);
setCourseNumber(courseNumber);
setCourseMode(courseMode);
setMeetingDay(meetingDay);
setMeetingTime(meetingTime);
setCapacity(capacity);
setEnrollment(enrollment);
setID(ID);
}
//STUDENT ENROLL ARRAY
List < StudentEnrollee > studentList = new ArrayList < StudentEnrollee > ();
public int getStudent() {
return student;
}
public void addStudent(StudentEnrollee studentObject) {
studentList.add(studentObject);
}
//LOCATING PERSON
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
//Delete person
public void deletePerson(String studentID) {
ClassSection personObject = locatePerson(studentID); // we'll use our locatePerson method find the index of a Person with a given socSecNum.
if (personObject != null) studentList.remove(personObject); // if element i contains the target SSN, remove it.
}
//DISPLAY LIST OF ENROLLEE
public void displayListV1() {
for (int i = 0; i < studentList.size(); i++) // the old way
{
System.out.println(studentList.get(i) + "\n");
}
}
//CRN
public int getCrn() {
return crn;
}
void setCrn(int classCrn) {
this.crn = classCrn;
}
//DEPARTMENT CODE
public String getDepartmentCode() {
return departmentCode;
}
void setDepartmentCode(String classDepartmentCode) {
this.departmentCode = classDepartmentCode;
}
//COURSE NUMBER
public int getCourseNumber() {
return courseNumber;
}
void setCourseNumber(int classCourseNumber) {
this.courseNumber = classCourseNumber;
}
//COURSE LOCATION
public String getCourseMode() {
return courseMode;
}
public void setCourseMode(String classCourseMode) {
this.courseMode = classCourseMode;
}
//MEETING DAY
public String getMeetingDay() {
return meetingDay;
}
public void setMeetingDay(String classMeetingDay) {
this.meetingDay = classMeetingDay;
}
//MEETING TIMES
public String getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(String classMeetingTime) {
this.meetingTime = classMeetingTime;
}
//CAPACITY
public int getCapacity() {
return capacity;
}
public void setCapacity(int classCapacity) {
this.capacity = classCapacity;
}
//ENROLLMENT
public int getEnrollment() {
return enrollment;
}
public void setEnrollment(int classEnrollment) {
this.enrollment = classEnrollment;
}
//INSTRUCTOR ID
public int getID() {
return ID;
}
public void setID(int instructorID) {
this.ID = instructorID;
}
//TO STRING METHOD
public String toString() {
return ("CRN :" + crn + "\n" +
"Department :" + departmentCode + "\n" +
"Course Number :" + courseNumber + "\n" +
"Instructional mode :" + courseMode + "\n" +
"Meeting days :" + meetingDay + "\n" +
"Meeting times :" + meetingTime + "\n" +
"Capacity :" + capacity + "\n" +
"Enrollment :" + enrollment + "\n" +
"Instructor’s ID :" + ID + "\n");
}
}
Driver
public class ClassDriver {
public static void main(String[] args) {
ClassSection firstInstance = new ClassSection(20008, "CHM", 000, "Online", "N/A", "N/A", 30, 21, 231);
ClassSection secondInstance = new ClassSection();
ClassSection addToList = new ClassSection();
StudentEnrollee studentObj1 = new StudentEnrollee();
StudentEnrollee studentObj2 = new StudentEnrollee();
StudentEnrollee studentObj3 = new StudentEnrollee();
studentObj1.setGrade(5);
studentObj1.setID(230);
studentObj2.setGrade(76);
studentObj2.setID(45);
studentObj3.setGrade(2);
studentObj3.setID(34);
addToList.addStudent(studentObj1);
addToList.addStudent(studentObj2);
addToList.addStudent(studentObj3);
addToList.deletePerson("45");
addToList.displayListV1();
System.out.println(firstInstance.toString());
System.out.println(secondInstance.toString());
}
}
I think it should be:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
You are trying to use a method from subclass in superclass, so you got the error that this method is not defined. You can use all method of superclass in subclasses, but it doesn't work another way.
The getStudentID() method is declared in class StudentEnrollee. In the code below, personObject, which is defined as a ClassSection object, does not have access to it.
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
The solution can vary based on your program logic, but the straightforward way is to replace ClassSection with StudentEnrollee:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
I would like to implement rather simple task. There are 2 queues (both have limited capacity): BlockingQueue<String> source and BlockingQueue<String> destination. There are 2 types of threads: Producer producer produces a message and stores at the BlockingQueue<String> source. The second - Replacer replacer picks from the source, transforms a message and inserts it into the BlockingQueue<String> destination.
Two questions/issues:
I am not sure that I have correctly implemented the following requirement: transfer messages from the source to destination if the source is not empty and destination is not full.
After finishing my program, there is a still running thread called - "Signal Dispatcher". How can I terminate it properly? My program doesn't terminate properly.
Here are the implementations of the relative entities:
Implementation of the source/destination queues.
public class BlockingQueueImpl<E> implements BlockingQueue<E> {
private volatile Queue<E> storage = new PriorityQueue<>();
private volatile int capacity;
private volatile int currentNumber;
public BlockingQueueImpl(int capacity) {
this.capacity = capacity;
this.storage = new PriorityQueue<E>(capacity);
}
#Override
public synchronized void offer(E element) {
while (isFull()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
currentNumber++;
storage.add(element);
notifyAll();
}
#Override
public synchronized E poll() {
while (isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
currentNumber--;
notifyAll();
return storage.poll();
}
#Override
public int size() {
return capacity;
}
public synchronized boolean isFull(){
return currentNumber > capacity;
}
public synchronized boolean isEmpty(){
return currentNumber == 0;
}
}
Implementation of the producer
public class Producer implements Runnable {
BlockingQueue<String> source;
String threadName;
public Producer(BlockingQueue<String> source, String threadName) {
this.source = source;
this.threadName = threadName;
}
#Override
public void run() {
while (!source.isFull()) {
source.offer(Utilities.generateMessage(threadName));
}
}
}
Implementation of the consumer
public class Replacer implements Runnable {
BlockingQueue<String> source;
BlockingQueue<String> destination;
String threadName;
public Replacer(BlockingQueue<String> source,
BlockingQueue<String> destination,
String threadName) {
this.source = source;
this.destination = destination;
this.threadName = threadName;
}
public synchronized void replace() {
destination.offer(Utilities.transformMessage(threadName, source.poll()));
}
private boolean isRunning() {
return (!destination.isFull()) && (!source.isEmpty());
}
#Override
public void run() {
while (isRunning()) {
replace();
}
}
}
And helper class
public class Utilities {
public static final int NUMBER_OF_PRODUCER_THREADS = 3;
public static final int NUMBER_OF_REPLACER_THREADS = 1000;
public static final int NUMBER_OF_MESSAGES_TO_READ = 1000;
public static final int STORAGE_CAPACITY = 100;
public static String transformMessage(String threadName, String messageToTransform) {
String[] splittedString = messageToTransform.split(" ");
String newMessage = "Thread #" + threadName + " transferred message " + splittedString[splittedString.length - 1];
return newMessage;
}
public static String generateMessage(String threadName) {
return "Thread #" + threadName + " generated message #" + threadName;
}
public static void spawnDaemonThreads(String threadName,
int numberOfThreadsToSpawn,
BlockingQueue<String> source,
BlockingQueue<String> destination) {
if (destination == null) {
for (int i = 1; i < numberOfThreadsToSpawn + 1; i++) {
String name = threadName + i;
Producer producer = new Producer(source, name);
Thread threadProducer = new Thread(producer);
threadProducer.setName(name);
threadProducer.setDaemon(true);
threadProducer.start();
}
} else {
for (int i = 1; i < numberOfThreadsToSpawn + 1; i++) {
String name = threadName + i;
Replacer replacer = new Replacer(source, destination, name);
Thread threadProducer = new Thread(replacer);
threadProducer.setName(name);
threadProducer.setDaemon(true);
threadProducer.start();
}
}
}
}
Main class:
public class Main {
public static void main(String[] args) {
BlockingQueue<String> source = new BlockingQueueImpl<>(Utilities.STORAGE_CAPACITY);
BlockingQueue<String> destination = new BlockingQueueImpl<>(Utilities.STORAGE_CAPACITY);
// Create, configure and start PRODUCER threads.
Utilities.spawnDaemonThreads("Producer", Utilities.NUMBER_OF_PRODUCER_THREADS, source, null);
// Create, configure and start REPLACER threads.
Utilities.spawnDaemonThreads("Replacer", Utilities.NUMBER_OF_REPLACER_THREADS, source, destination);
// Read NUMBER_OF_MESSAGES_TO_READ from destination.
for (int i = 1; (i < Utilities.NUMBER_OF_MESSAGES_TO_READ) && !destination.isEmpty(); i++) {
System.out.println(destination.poll());
}
}
}
Here is working code.
/**
* Class {#code BlockingQueueImpl} is the implementation of the Blocking Queue.
* This class provides thread-safe operations
* {#code public void offer(E element)} and {#code public E poll()}
*/
public class BlockingQueueImpl<E> implements BlockingQueue<E> {
private volatile Queue<E> storage = new PriorityQueue<>();
private volatile int capacity;
private volatile int currentNumber;
public BlockingQueueImpl(int capacity) {
this.capacity = capacity;
this.storage = new PriorityQueue<E>(capacity);
}
#Override
public synchronized void offer(E element) {
while (isFull()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.add(element);
currentNumber++;
notifyAll();
}
#Override
public synchronized E poll() {
E polledElement;
while (isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notifyAll();
polledElement = storage.poll();
currentNumber--;
return polledElement;
}
#Override
public int size() {
return capacity;
}
public synchronized boolean isFull(){
return currentNumber >= capacity;
}
public synchronized boolean isEmpty(){
return currentNumber == 0;
}
}
public class Producer implements Runnable {
BlockingQueue<String> source;
String threadName;
public Producer(BlockingQueue<String> source, String threadName) {
this.source = source;
this.threadName = threadName;
}
#Override
public void run() {
while (!source.isFull()) {
source.offer(Utilities.generateMessage(threadName));
}
}
}
public class Replacer implements Runnable {
BlockingQueue<String> source;
BlockingQueue<String> destination;
String threadName;
public Replacer(BlockingQueue<String> source,
BlockingQueue<String> destination,
String threadName) {
this.source = source;
this.destination = destination;
this.threadName = threadName;
}
public synchronized void replace() {
destination.offer(Utilities.transformMessage(threadName, source.poll()));
}
//Continue execution of a thread if a destination is not full and source is not empty.
private boolean isRunning() {
return (!destination.isFull()) && (!source.isEmpty());
}
#Override
public void run() {
while (isRunning()) {
replace();
}
}
}
public class Utilities {
public static final int NUMBER_OF_PRODUCER_THREADS = 3;
public static final int NUMBER_OF_REPLACER_THREADS = 1000;
public static final int NUMBER_OF_MESSAGES_TO_READ = 1000;
public static final int STORAGE_CAPACITY = 100;
public static String transformMessage(String threadName, String messageToTransform) {
String[] splittedString = messageToTransform.split(" ");
String newMessage = "Thread #" + threadName + " transferred message " + splittedString[splittedString.length - 1];
return newMessage;
}
public static String generateMessage(String threadName) {
return "Thread #" + threadName + " generated message #" + threadName;
}
public static void spawnDaemonThreads(String threadName,
int numberOfThreadsToSpawn,
BlockingQueue<String> source,
BlockingQueue<String> destination) {
if (destination == null) {
for (int i = 1; i < numberOfThreadsToSpawn + 1; i++) {
String name = threadName + i;
Producer producer = new Producer(source, name);
Thread threadProducer = new Thread(producer);
threadProducer.setName(name);
threadProducer.setDaemon(true);
threadProducer.start();
}
} else {
for (int i = 1; i < numberOfThreadsToSpawn + 1; i++) {
String name = threadName + i;
Replacer replacer = new Replacer(source, destination, name);
Thread threadProducer = new Thread(replacer);
threadProducer.setName(name);
threadProducer.setDaemon(true);
threadProducer.start();
}
}
}
}