the matt jones website.‎ > ‎Java‎ > ‎

Java Threads - run() and start()

Some people may find this by searching "How to run more than one thread in Java" or second thread will not run.

A common error for beginners in Java Thread Programming is to use Thread.run() instead of Thread.start() and wonder why the second thread is not starting.

Thread.run() just executes the code defined in the run() method in the same thread as the object calling .run()
Thread.start() runs the code in a thread and then continues with the next line of code from the object starting the thread.

Let's look at an example:

package threadExample

public class Main extends Thread {

    public static void main(String[] args) {

        Thread thread1 = new Thread() {

            @Override
            public void run() {
                while (true) {
                    System.out.println("One");
                }
            }
        };
       
        Thread thread2 = new Thread() {

            @Override
            public void run() {
                while (true) {
                    System.out.println("Two");

                    }
                }
           
        };
        thread1.run();
        thread2.run();
    }
}

The above code will print out something like:
One
One
One
One
One
One
One
One
One
One
.
.
.

As thread1 will never return control back to Main.

If we were to change:
        thread1.run();
        thread2.run();
to
        thread1.start();
        thread2.start();
Then the behavior will be more like this:
One
One
One
Two
Two
Two
One
One
One
Two
Two
Two
.
.
.

Comments