Question

1.) Analyze the Java code PrimeFinder. How long did it take your system to calculate the...

1.) Analyze the Java code PrimeFinder.

  1. How long did it take your system to calculate the primes?
  2. How did you know the answer (what is Thread.sleep(1000) doing in the 'while' loop?)
  3. Take a snapshot of the output

_______________________________________________________________

Below is the "PrimeFinder" java code:

1: package com.java24hours;
2:   
3: public class PrimeFinder implements Runnable {
4: Thread go;
5: StringBuffer primes = new StringBuffer();
6: int time = 0;
7:
8: public PrimeFinder() {
9: start();
10: while (primes != null) {
11: System.out.println(time);
12: try {
13: Thread.sleep(1000);
14: } catch (InterruptedException exc) {
15: // do nothing
16: }
17: time++;
18: }
19: }
20:
21: public void start() {
22: if (go == null) {
23: go = new Thread(this);
24: go.start();
25: }
26: }
27:
28: public void run() {
29: int quantity = 1_000_000;
30: int numPrimes = 0;
31: // candidate: the number that might be prime
32: int candidate = 2;
33: primes.append("\nFirst ").append(quantity).append(" primes:\n\n");
34: while (numPrimes < quantity) {
35: if (isPrime(candidate)) {
36: primes.append(candidate).append(" ");
37: numPrimes++;
38: }
39: candidate++;
40: }
41: System.out.println(primes);
42: primes = null;
43: System.out.println("\nTime elapsed: " + time + " seconds");
44: }
45:
46: public static boolean isPrime(int checkNumber) {
47: double root = Math.sqrt(checkNumber);
48: for (int i = 2; i <= root; i++) {
49: if (checkNumber % i == 0) {
50: return false;
51: }
52: }
53: return true;
54: }
55:
56: public static void main(String[] arguments) {
57: new PrimeFinder();
58: }
59: }

Homework Answers

Answer #1

To understand this, we need to undersatnd the concept of threads in Java.

Threads can be used to perform tasks faster. 2 Threads can run concurrently in Java. But here if we see the program in Debug mode-

There are 2 threads- 1. Main thread (for main method) and another is the thread which got started at line 24: go.start();

Main thread can be controlled by CurrentThread() method, which is not called anywhere in this program. So the main thread keeps on executing the below piece of code, untill primes gets some value from the run method. (Please note there are 2 threads working simultaneously. 1 running the below code and the other running the run() method)

while (primes != null) {
11: System.out.println(time);
12: try {
13: Thread.sleep(1000);
14: } catch (InterruptedException exc) {
15: // do nothing
16: }
17: time++;
18: }

So before the run() method thread could calculate all the first 1000000 prime numbers. The main thread gets into action and finds that primes is no longer != null and hence the while loop while (primes != null) breaks, treminating the program. And thus we are not able to see the prime numebrs.

If you want to see the prime numbers reduce the
29: int quantity = 1_000_000; to 1000.

2. Why Thread.Sleep() ?

So If we do not use Thread.Sleep(), the main thread will keep executing and will not give a chance to the run() thread to add values to primes. So in this manner while (primes != null) will always hold true and the program might go to an infinite loop. Adding Thread.sleep() give a chance to the other thread to execute and saves the program from going to infinite loop.

Output in my system- The output will depend on the RAM and storage and other performance of the laptop/desktop. So our outputs might varry.

The output gives

0
1
2
3
4
5
6
7
8
9
10
11
12

Know the answer?
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
Similar Questions
2.) Analyze the modified Java code PrimeFinderInterupt Make this program to RUN and provide a screenshot...
2.) Analyze the modified Java code PrimeFinderInterupt Make this program to RUN and provide a screenshot of the output Describe the additional functionality of the PrimeFinderInterrupt NOTE IF your original PrimeFinder ran faster than 7 seconds, change the code line: "if (++index > 7 )" to have a number less than the time to run your original code. _______________________________________________________________ Below is the "PrimeFinderInterupt" java code: package com.java24hours; public class PrimeFinderInterrupt implements Runnable { Thread go; StringBuffer primes = new StringBuffer();...
In Java ReWrite the for loop program code example 3, above as a while loop. Code...
In Java ReWrite the for loop program code example 3, above as a while loop. Code Example 3 – Try it import java.util.Scanner; public static void main(String args[]) { int count = 0; int maxNumber = 0; int enteredNumber = -9999999; System.out.println("This program determines which entered number is the largest "); System.out.println("Enter count of numbers to check: "); Scanner scanIn = new Scanner(System.in); double count = scanIn.nextDouble(); scanIn.close(); // Print out message – input number – compare to see if...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have this much public class Main { int WIDTH = 0; double HEIGHT = 0; public static void drawSmileyFaces() { System.out.println(" :-):-):-):-):-):-)"); } public static void main (String[] args) { for (int WIDTH = 0; WIDTH < 3; WIDTH++ ) { for(double HEIGHT = 0; HEIGHT < 2; HEIGHT++) { drawSmileyFaces(); } } } } I am pretty sure that alot of this is wrong...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { flavor = s; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         System.out.println(pepper.getFlavor());     } } a. a class variable b. a constructor c. a local object variable d....
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
Analyze this code and run it, if there are any issues note them and fix them,...
Analyze this code and run it, if there are any issues note them and fix them, if not give the output and Big O notation runtime: public class PrintBits { public static void printBits(int a) { try { String str = Integer.toBinaryString((Integer) a); for(int i = 0; i < str.length(); i++){ System.out.print (str.charAt(i)); } } catch (ClassCastException e) { throw new RuntimeException ("Argument is not an Integer"); } } public static void main (String[] args){ printBits (-17); System.out.println(); printBits (17);...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
I wrote the following java code with the eclipse ide, which is supposed to report the...
I wrote the following java code with the eclipse ide, which is supposed to report the number of guesses it took to guess the right number between one and five. Can some repost the corrected code where the variable "guess" is incremented such that the correct number of guesses is displayed? please test run the code, not just look at it in case there are other bugs that exist. import java.util.*; public class GuessingGame {    public static final int...
do a code trace on how a key gets deleted package interview; import java.util.*; public class...
do a code trace on how a key gets deleted package interview; import java.util.*; public class binarySearchTree { Node root; void insert(int key) { root = insertRec(root,key); } void delete(int key) { root = deleteRec(root,key); } Node insertRec(Node root, int key) { if(root == null) { root = new Node(key); return root; } if(key < root.key) { root.leftChild = insertRec(root.leftChild,key); } else if(key > root.key){ root.rightChild = insertRec(root.rightChild,key); } return root; } Node deleteRec(Node root, int key) { if(root ==...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT