3 Replies Latest reply on Jul 4, 2011 11:49 PM by sabre150

    Thread#start v.s. Thread#run

    Johnny_hunter
      Hello all:

      I noticed that some code calls Thread#run() as opposed to Thread#start(), is there a particular reason to choose one over the other?

      From the doc it seems that the thread use run() when it is passed a Runnable object via its constructor.

      Thanks,
      John
        • 1. Re: Thread#start v.s. Thread#run
          796440
          start() starts a new thread of execution, while run() is just a plain old method defined by Runanble. It was a design error on Sun's part to even give Thread a run() method in the first place.

          Unless you're writing your own thread pool, you'll never call run() directly.
          • 2. Re: Thread#start v.s. Thread#run
            Johnny_hunter
            thanks, jverd. I wouldn't use run() myself, so it seems odd someone uses it like that.
            • 3. Re: Thread#start v.s. Thread#run
              sabre150
              Johnny_hunter wrote:
              thanks, jverd. I wouldn't use run() myself, so it seems odd someone uses it like that.
              I have a class called SyncPipe which is a Runnable. The constructor accepts in InputStream and an OutputStream and the run() method copies the InputStream content to the OutputStream. I use this mainly with Runtime.exec() and ProcessBuilder for handling the Process 'stdout', 'stderr' and sometimes 'stdin'. Sometimes it is necessary to have one or more of these processed by independent threads so then I just start a Thread using a SyncPipe as the Runnable. Other times I can use the thread that started the Process so I then invoke SyncPipe.run() directly.

              Now I could have created a separate method or class for when I don't need to start a new Thread but I chose to leverage my existing code.