Solved

java programming in thread

Posted on 2004-10-03
12
219 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
 

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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

760 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now