Solved

java programming in thread

Posted on 2004-10-03
12
221 Views
Last Modified: 2010-03-31
//This file create Several Threads as well as performing file i/o.

import java.util.*;
import java.io.*;

public class RandWord extends Thread
{
String displayString;
boolean canCount;
static PrintStream outfile=null;
static int numwords;
static FileOutputStream ff=null;
Random random;
static File f=null;

static
{
try
      {
                 File f=new File("c:/orisree/java/plum.txt");
                ff=new FileOutputStream(f);
       PrintStream outfile=new PrintStream(ff);
       numwords=0;
                }
catch(FileNotFoundException fp)
{
       System.out.println("File not found");
}
}

public  RandWord(String dispString, boolean shouldCount)
{
     displayString = dispString;
     canCount = shouldCount;
     Random random=new Random();
}

public void run()
{
long waitTime;
System.out.println("Starting "+displayString);
while (numwords<5)
      {
              try{
                 outfile.println(displayString);
      }
      catch(NullPointerException ne)
      {
          System.out.println("Null Exception"+ne);
      }
      if(canCount)
      {
              numwords=numwords+1;
              System.out.println("Numwords"+numwords);
       }
        try
       {            
                          waitTime=1+(long)(Math.random()*5000);
                System.out.println("Stopping "+displayString);
               Thread.currentThread().sleep(waitTime);
       }
      catch(InterruptedException ie)
      {
               System.out.println(" Exception"+ie);
      }
}
}

public  static void main(String args[])
{


      RandWord[] threads=new RandWord[27];
      for (int i=65; i < 91; i++)
      {

                  threads[i-65] = new RandWord(String.valueOf((char)i),false);
                            threads[i-65].start();
                           System.out.println("Stopping"+(char)i);
                  try{
            Thread.currentThread().sleep(1+(int)Math.random()*50);
            }
                  catch(InterruptedException  ie)
                  {      
            System.out.println(" Exception"+ie);
                              }
}
                            try
                          {
                  threads[26] = new RandWord(".",true);
                  threads[26].start();
                  Thread.currentThread().sleep(1+(int)Math.random()*50);
                            }
                  catch(InterruptedException  ie)
                   {
            System.out.println(" Exception"+ie);
                                }
                       finally{
            try{
            ff.close();
            outfile.close();
            }
            catch(Exception ff)
            {
            }
}
}

}
In the above program,am getting  null pointerException while trying to write in the file "plum.txt"
0
Comment
Question by:sraveend
  • 5
  • 5
  • 2
12 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 12213283
You're hiding the instance variable. Change

>>PrintStream outfile=new PrintStream(ff);

to
     outfile=new PrintStream(ff);
0
 

Author Comment

by:sraveend
ID: 12213665
i tried to use random object for selecting random numbers,but it went wrong,pls give some hint
0
 

Author Comment

by:sraveend
ID: 12213715
In the above program i get all alphabets in the file only once,pls explain?
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

Author Comment

by:sraveend
ID: 12213736
Please explain me the logic of the above program
0
 
LVL 92

Expert Comment

by:objects
ID: 12214043
try this:

//This file create Several Threads as well as performing file i/o.

import java.util.*;
import java.io.*;

public class RandWord extends Thread
{
String displayString;
boolean canCount;
static PrintStream outfile=null;
static int numwords;
static FileOutputStream ff=null;
Random random;
static File f=null;

public  RandWord(String dispString, boolean shouldCount)
{
     displayString = dispString;
     canCount = shouldCount;
     Random random=new Random();
}

public void run()
{
long waitTime;
System.out.println("Starting "+displayString);
while (numwords<5)
     {
              try{
                outfile.println(displayString);
     }
     catch(NullPointerException ne)
     {
         System.out.println("Null Exception"+ne);
     }
     if(canCount)
     {
             numwords=numwords+1;
             System.out.println("Numwords"+numwords);
      }
       try
      {          
                          waitTime=1+(long)(Math.random()*5000);
               System.out.println("Stopping "+displayString);
              Thread.currentThread().sleep(waitTime);
      }
     catch(InterruptedException ie)
     {
              System.out.println(" Exception"+ie);
     }
}
}

public  static void main(String args[]) throws IOException
{

   File f=new File("c:/orisree/java/plum.txt");
   ff=new FileOutputStream(f);
   outfile=new PrintStream(ff);
   numwords=0;

     RandWord[] threads=new RandWord[27];
     for (int i=65; i < 91; i++)
     {

                 threads[i-65] = new RandWord(String.valueOf((char)i),false);
                            threads[i-65].start();
                           System.out.println("Stopping"+(char)i);
                 try{
          Thread.currentThread().sleep(1+(int)Math.random()*50);
          }
                 catch(InterruptedException  ie)
                 {    
          System.out.println(" Exception"+ie);
                             }
}
                            try
                          {
                 threads[26] = new RandWord(".",true);
                 threads[26].start();
                 Thread.currentThread().sleep(1+(int)Math.random()*50);
                            }
                 catch(InterruptedException  ie)
                  {
          System.out.println(" Exception"+ie);
                               }
                     finally{
          try{
          ff.close();
          outfile.close();
          }
          catch(Exception ff)
          {
          }
}
}

}
0
 
LVL 92

Expert Comment

by:objects
ID: 12214061
what the code does is start a number of threads, one for each letter in the alphabet plus ".".
these threads will loop until the thread for "." has looped 5 times.
For each loop the letter is written to the output file.

0
 

Author Comment

by:sraveend
ID: 12214270
But the out file contains the Alphabet letters only once,though i've taken off the static initializer.....
0
 
LVL 92

Expert Comment

by:objects
ID: 12214305
what did you want it to do exactly?
0
 
LVL 92

Accepted Solution

by:
objects earned 300 total points
ID: 12215272
> But the out file contains the Alphabet letters only once

your problem is that you close the output file before all the threads have finished.

try the following before closing the file to wait until all the threads have completed:

for (int i=0; i<threads.length; i++)
{
   threads[i].join();
}
0
 

Author Comment

by:sraveend
ID: 12217054
My question is displayString stores Alphabets more than once,why file contents are having only one set of alphabates?
just i want to clear my doubts?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12220199
:-)

Strictly speaking, sraveend, i answered the question. Others answered *other* questions
0
 
LVL 92

Expert Comment

by:objects
ID: 12221181
Glad I could help :)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 78
java stored proc example 9 32
servlet web applications   metadata-complete="true" or false 3 41
Facing this issue for maven proxy setting 2 12
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question