Solved

java programming in thread

Posted on 2004-10-03
12
224 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
Industry Leaders: 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!

 

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

734 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