1

I have one Thread that extends another. In the superclass there are two methods that print out trivial data about a thread. The thread that extends this superclass also calls these two methods which lies my issue. I wish to output all the data produced by these two methods to an output file, however due to the fact that my superclass extends the thread class, it implements runnable. Due to this I cannot throw any exception from a threads run method in order to possibly print line by line to an output file(ie: throw IOException). Keep in mind I wish to print output line by line and not using methods such as:

PrintStream out = new PrintStream(new FileOutputStream("output4.txt"));
System.setOut(out);

I instead wish to do something along the lines of using a FileWriter and PrintWriter to output each line of the BaseThread to one file(for each Thread instance).

static class BaseThread extends Thread
{
    public synchronized void info1()
    {
    //print some thread data to an outputfile
    }
    public synchronized void info2()
    {
    //print some thread data to an outputfile
    }
}
public class CallMyThreads
{
     public static void main(String[]args)
     {
         Thread1 t1 = new Thread1();
         Thread1 t2 = new Thread1();

         t1.start();
         t2.start();

         t1.join();
         t2.join();
     }
 static class Thread1 extends BaseThread //inner class
 {
    public void run() // <--- Cannot throw exception here for IO
    {
       info1(); //wish for each instance to print this to a file(1 file all concatenated together for each thread)
       info2();//wish for each instance to print this to a file(1 file all concatenated together for each thread)
    }
 } //close Thread1
 }//close main thread

Any work around with this situation would be appreciated.

JmanxC
  • 377
  • 2
  • 16

1 Answers1

0

First off: don't extend Thread. See this question for a lot more detail.


You are better off implementing Callable, which allows you to throw checked exceptions:

static class BaseThread { ... }

static class Thread1 extends BaseThread implements Callable<Void> //inner class
{
  @Override public Void call() throws IOException
  {
    info1();
    info2();
    return null;  // You have to return something from a Callable.
  }
}

Now you can invoke this using an ExecutorService:

ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> f1 = executor.submit(new Thread1());
Future<?> f2 = executor.submit(new Thread1());
executor.shutdown();

f1.get();  // Instead of join.
f2.get();

Future.get() throws a number of checked exceptions, but the one of note is ExecutionException, which indicates an uncaught exception occurred during execution; you can get that exception from the getCause() of the ExecutionException.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243