Counting Loop Using Threads (Java)

Discussion in 'Software' started by Adola, Apr 5, 2011.

  1. Adola

    Adola Private E-2

    Hi,

    The following is a simple code to display a count of a loop of 100:

    Code:
    public class count {
      public static void main(String[] args){
       int count = 0;
       int i = 0;
    
       while (i < 100) {
    	  i++;
    	  count++;
    	  }
       System.out.println("Number of values: " + count);
      }
    }
    
    I would like to use two threads to do the counting concurrently. The first thread starts every 3 seconds while the other one starts say every 5 seconds. Then display how many numbers each thread was able to count out of the 100. How do I accomplish this?

    Any help would be truly appreciated! :)
     
  2. Adola

    Adola Private E-2

    The following is a basic code to read integers from a file:

    Code:
    import java.util.Scanner;
    import java.io.*;
    
    class FileReadingApp
    {
      public static void main (String[] args) throws IOException
      {
        int count = 0;
    
        File file = new File("data.txt");
        Scanner scan = new Scanner( file );
        while(scan.hasNextInt())
        {
          double num = scan.nextInt();
          count++;
        }
          System.out.println("Number of integers is: " + count);
      }
    
    }
    
    Finding a multithreading solution for this problem using the loop example or the file example should be enough to get me started. Thanks!
     
  3. Wyatt_Earp

    Wyatt_Earp MajorGeek


MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds