Question

According to this cord use LongFifoWait Notify thread methord in CircularArrayLongFifo class. According to this cord...

According to this cord use LongFifoWait Notify thread methord in CircularArrayLongFifo class. According to this cord use LongFifoWait Notify thread methord in CircularArrayLongFifo class.

public class CandidateGenerator {
private final LongFifo outputFifo;

public CandidateGenerator(LongFifo outputFifo) {
this.outputFifo = outputFifo;

Runnable r = new Runnable() {
@Override
public void run() {
runWork();}};

Thread t = new Thread(r, "CandidateGenerator");
t.start() }

private void runWork() {
try {
outputFifo.add(2);
long number = 3;
while ( true ) {
outputFifo.add(number);
number += 2;}
} catch ( InterruptedException x ) { // ignore and let the thread die}}}
================================================

package com.abc.prime;

/*Implementation of {@link LongFifo} which uses a circular array internally. Look at the documentation in LongFifo to see how the methods are supposed to work. The data is stored in the slots array. count is the number of items currently in the FIFO. When the FIFO is not empty, head is the index of the next item to remove. When the FIFO is not full, tail is the index of the next available slot to use for an added item. Both head and tail need to jump to index 0 when they "increment" past the last valid index of slots (this is what makes it circular). See <a href="https://en.wikipedia.org/wiki/Circular_buffer">Circular Buffer on Wikipedia</a> for more information.
*/
public class CircularArrayLongFifo implements LongFifo {
// do not change any of these fields:
private final long[] slots;
private int head;
private int tail;
private int count;
private final Object lockObject;

// this constructor is correct as written - do not change
public CircularArrayLongFifo(int fixedCapacity,
Object proposedLockObject) {

lockObject =
proposedLockObject != null ? proposedLockObject : new Object();

slots = new long[fixedCapacity];
head = 0;
tail = 0;
count = 0;}

// this constructor is correct as written - do not change
public CircularArrayLongFifo(int fixedCapacity) {
this(fixedCapacity, null);}

// this method is correct as written - do not change
@Override
public int getCount() {
synchronized ( lockObject ) {
return count; }}

@Override
public boolean isEmpty() {
synchronized ( lockObject ) {
return count == 0; }}

@Override
public boolean isFull() {
synchronized ( lockObject ) {
return count == slots.length;} }

@Override
public void clear() {
synchronized ( lockObject ) {
// No need - just keep the old junk (harmless):
// Arrays.fill(slots, 0);
head = 0;
tail = 0;
count = 0;}}

@Override
public int getCapacity() {
return slots.length;}

@Override
public void add(long value) throws InterruptedException {}

@Override
public long remove() throws InterruptedException {
return 0L;}

// this method is correct as written - do not change
@Override
public Object getLockObject() {
return lockObject;}}
============================================

public interface LongFifo {
/** Returns the number if items currently in the FIFO. */
int getCount();

/** Returns true if {@link #getCount()} == 0. */
boolean isEmpty();

/** Returns true if {@link #getCount()} == {@link #getCapacity()}. */
boolean isFull();

/** Removes any and all items in the FIFO leaving it in an empty state. */
void clear();

/*Returns the maximum number of items which can be stored in this FIFO. This value never changes.*/
int getCapacity();

/*Add the specified item to the fifo. If currently full, the calling thread waits until there is space and then adds the item. If this method doesn't throw InterruptedException, then the item was successfully added. */
void add(long value) throws InterruptedException;

/* Removes and returns the next item. If currently empty, the calling thread waits until another thread adds an item. If this method doesn't throw InterruptedException, then the item was successfully removed. */
long remove() throws InterruptedException;

/*Returns a reference to use for synchronized blocks which need to call multiple methods without other threads being able to get in. Never returns null.*/
Object getLockObject(); }
====================================================

public class NanoTimer {
private final double NS_PER_MILLISECOND = 1000000.0;
private final double NS_PER_SECOND = NS_PER_MILLISECOND * 1000.0;
private final double NS_PER_MINUTE = NS_PER_SECOND * 60.0;
private final double NS_PER_HOUR = NS_PER_MINUTE * 60.0;
private final double NS_PER_DAY = NS_PER_HOUR * 24.0;

private long nsStartTimeOfInterval;
private long nsTotalOfStoppedIntervals = 0L;
private boolean paused = true;

// private, use createXYZ methods
private NanoTimer() {}

public static NanoTimer createStarted() {
NanoTimer timer = new NanoTimer();
timer.start();
return timer;}

public static NanoTimer createStopped() {
return new NanoTimer(); }

public synchronized void start() {
if ( paused ) {
paused = false;
nsStartTimeOfInterval = System.nanoTime();}}

public synchronized void stop() {
if ( !paused ) {
paused = true;
nsTotalOfStoppedIntervals += System.nanoTime() - nsStartTimeOfInterval;}}

public synchronized void reset() {
stop();
nsTotalOfStoppedIntervals = 0L; }

public synchronized long getElapsedNanoseconds() {
return nsTotalOfStoppedIntervals +
(paused ? 0 : System.nanoTime() - nsStartTimeOfInterval);}

public double getElapsedMilliseconds() {
return getElapsedNanoseconds() / NS_PER_MILLISECOND;}

public double getElapsedSeconds() {
return getElapsedNanoseconds() / NS_PER_SECOND; }

public double getElapsedMinutes() {
return getElapsedNanoseconds() / NS_PER_MINUTE; }

public double getElapsedHours() {
return getElapsedNanoseconds() / NS_PER_HOUR; }

public double getElapsedDays() {
return getElapsedNanoseconds() / NS_PER_DAY; }}
============================================================

public class PrimeChecker {
private final LongFifo inputFifo;
private final LongFifo outputFifo;

public PrimeChecker(LongFifo inputFifo, LongFifo outputFifo) {
this.inputFifo = inputFifo;
this.outputFifo = outputFifo;

new Thread(new Runnable() {
@Override
public void run() {
runWork();}
}, "PrimeChecker").start();}

private void runWork() {
try {
while ( true ) {
long candidate = inputFifo.remove();
if ( isPrime(candidate) ) {
outputFifo.add(candidate);}}
} catch ( InterruptedException x ) {
// ignore and let the thread die} }

private boolean isPrime(long number) {
if ( number < 2 ) {
return false;}

long divisorLimit = 1 + (long) Math.sqrt(number);
for ( long divisor = 2; divisor < divisorLimit; divisor++ ) {
if ( number % divisor == 0 ) {
return false;}}
return true; }}
======================================================

public class PrimeMain {
@SuppressWarnings("unused")
public static void main(String[] args) {
LongFifo candidateFifo = new CircularArrayLongFifo(500000);
LongFifo primeFifo = new CircularArrayLongFifo(100);

System.out.println("loading up candidate fifo...");
new CandidateGenerator(candidateFifo);
while (!candidateFifo.isFull()) {
try {
Thread.sleep(200);
} catch ( InterruptedException x ) {
x.printStackTrace(); } }
System.out.println("DONE loading up candidate fifo...");

new PrimeChecker(candidateFifo, primeFifo);
//new PrimeChecker(candidateFifo, primeFifo);
//new PrimeChecker(candidateFifo, primeFifo);

new PrimePrinter(primeFifo); }}
================================================================

public class PrimePrinter {
private final LongFifo inputFifo;

public PrimePrinter(LongFifo inputFifo) {
this.inputFifo = inputFifo;

new Thread(new Runnable() {
@Override
public void run() {
runWork();}
}, "PrimePrinter").start();}

private void runWork() {
// take a prime off the "known to be prime" FIFO and print it out...
// ... if there aren't any, sleep a bit, then try again....
try {
NanoTimer timer = NanoTimer.createStarted();
int maxCountPerLine = 10;
int primeCount = 0;
int currCount = 0;
while ( true ) {
long primeNumber = inputFifo.remove();
primeCount++;
System.out.printf("%7d ", primeNumber);
currCount++;
if (currCount == maxCountPerLine) {
System.out.println();
currCount = 0;}
if (primeNumber > 100000L) {
if ( currCount > 0 ) {
System.out.println(); }
System.out.printf(
"Found %,d primes in %.5f seconds with " +
"the last one %,d%n",
primeCount, timer.getElapsedSeconds(), primeNumber);
return;}}
} catch ( InterruptedException x ) {
// ignore and let the thread die} }}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please comment below, If you find any difficulty in understanding

Please Upvote the answer, If you are impressed

Answer :

import java.util.*;
class arrayreversing
{
   public static void main(String args[])
   {
       Scanner sc=new Scanner(System.in);
       int n,i,j;
       System.out.println("Enter the Size of Array1 : ");
       n=sc.nextInt();
       int[] arr1=new int[n];
       int[] arr2=new int[n];
       for(i=0;i<n;i++)
       {
           System.out.println("Enter element "+i+" : ");
           arr1[i]=sc.nextInt();
       }
       System.out.println("Array1 Before reversing: ");
       for(i=0;i<arr1.length;i++)
       {
           System.out.println(arr1[i]);
       }
       j=n-1;
       for(i=0;i<n;i++)
       {
           arr2[i]=arr1[j--];
       }
       System.out.println("Array1 after reversing: ");
       for(i=0;i<arr2.length;i++)
       {
           System.out.println(arr2[i]);
       }
          
      
   }
}

Add a comment
Know the answer?
Add Answer to:
According to this cord use LongFifoWait Notify thread methord in CircularArrayLongFifo class. According to this cord...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 1. Analyze the following code: public class Test implements Runnable { public static void main(String[] args) { Thread t = new Thread(this); t.start(); } public void run() { System....

    1. Analyze the following code: public class Test implements Runnable { public static void main(String[] args) { Thread t = new Thread(this); t.start(); } public void run() { System.out.println("test"); } } 1. The code compiles but will not print anything since t does not invoke the run method. 2. The code will not compile since you cannot invoke "this" in a static method. 3. The program compiles, runs, and prints tests on the console. 2. What will the following example...

  • Need help writing Java code for this question. CircleFrame class is provided below. what happen after...

    Need help writing Java code for this question. CircleFrame class is provided below. what happen after u add the code and follow the requirement? It would be nice to be able to directly tell the model to go into wait mode in the same way that the model's notify method is called. (i.e. notify is called directly on the model, whereas wait is called indirectly through the suspended attribute.) Try altering the the actionPerformed method of the SliderListener innner class...

  • Consider the following codes: public class TestThread extends Thread {     public static void main(String[] args)...

    Consider the following codes: public class TestThread extends Thread {     public static void main(String[] args) {         TestThread thread = new TestThread();     }     @Override     public void run() {         printMyName();     }     private void printMyName() {         System.out.println("Thread is running");     } } Test Stem / Question Choices 1: What method should you invoke to start the thread TestThread? A: start() B: run() C: No. Thread will run automatically when executed. D: TestThread is not...

  • Exercise 1): take the program “InteractiveCounting” (attached). Your task is to change the implementation of both...

    Exercise 1): take the program “InteractiveCounting” (attached). Your task is to change the implementation of both the “ReadInput” and the “Count” classes. Currently these classes extends Thread. You should now use the Runnable interface to implement the thread. The output of the program should not change. I have also attached the class ThreadType2 to give you a working example on how to implement a thread using the Runnable interfacethe program is here package threadExamples; import java.util.Scanner; public class InteractiveCounting {...

  • Complete the CashRegister class by implementing the methods and adding the correct attributes (characteristics) as discussed...

    Complete the CashRegister class by implementing the methods and adding the correct attributes (characteristics) as discussed in class. Once complete, test the class using the CashRegisterTester class. Make sure you have 3 total items in the cash register. I have two classes, the first is CashRegisterTester below: public class CashRegisterTester { public static void main(String[] args) { //Initialize all variables //Construct a CashRegister object CashRegister register1 = new CashRegister(); //Invole a non-static method of the object //since it is non-static,...

  • Assignment (to be done in Java): Person Class: public class Person extends Passenger{ private int numOffspring;...

    Assignment (to be done in Java): Person Class: public class Person extends Passenger{ private int numOffspring; public Person() {    this.numOffspring = 0; } public Person (int numOffspring) {    this.numOffspring = numOffspring; } public Person(String name, int birthYear, double weight, double height, char gender, int numCarryOn, int numOffspring) {    super(name, birthYear, weight, height, gender, numCarryOn);       if(numOffspring < 0) {        this.numOffspring = 0;    }    this.numOffspring = numOffspring; } public int getNumOffspring() {   ...

  • instructions: Write a non-member method named bagScaler, which removes from a Bag all elements that occur...

    instructions: Write a non-member method named bagScaler, which removes from a Bag all elements that occur less than N times . The method returns the number of copies removed. For example, if B = {Bob, Joe, Bob, Ned, Bob, Ned, Kim}, then calling bagScaler(B, 3) removes Joe, Ned, and Kim making B = {Bob, Bob, Bob}, and returns 4 because it removed 2 copies of Ned, one of Joe, and one of Kim. Note: There's no iterator, but there is...

  • public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private...

    public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private int tail; Private int count;   } public void enqueue(E item) { if(isFull()){ return; } count++; elements[tail] = item; tail = (tail + 1) % size; } public E dequeue() { if(isEmpty()) return null; int ct = count-1; E cur = elements[head]; int index = 0; for(i=1;ct-->0;i++) { if(cur.compareTo(elements[head+i)%size])<0) cur = elements[(head+i)%size]; index = i; } } return remove((head+index%size); public E remove(int index) { E...

  • Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a...

    Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a string s as a parameter and returns true if the title of the string is equal to s. Create the same method for your library material copies. Note that it will need to be abstract in the LibraryMaterialCopy class MY CODE **************************************************************** LibraryCard: import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import    java.time.temporal.ChronoUnit; public class LibraryCard {    private String id;    private String cardholderName;   ...

  • NETBEANS JAVA BANK PROGRAM (TAKE SCREENSHOTS FROM NETBEANS INCLUDING OUTPUT PLEASE) Display the accounts for the...

    NETBEANS JAVA BANK PROGRAM (TAKE SCREENSHOTS FROM NETBEANS INCLUDING OUTPUT PLEASE) Display the accounts for the current displayed customer PLEASEEEEEEEEEE package bankexample; import java.util.UUID; public class Customer { private UUID id; private String email; private String password; private String firstName; private String lastName;    public Customer(String firstName, String lastName, String email, String password) { this.id = UUID.randomUUID(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT