Solved

java programming in thread

Posted on 2004-10-03
12
226 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

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…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

632 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