0

While writing a program using multi threading we had a method containing run method in different threads. They used thread.start instead of thread.run. Could someone explain what's the reason behind not calling the method by its name?

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • 1
    This is not an answer to your question but I would suggest you to manage threads with `Executors` https://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html – Radek Mar 19 '15 at 15:06
  • This seems to be answered here, have a look: [http://stackoverflow.com/questions/8579657/java-whats-the-difference-between-thread-start-and-runnable-run](http://stackoverflow.com/questions/8579657/java-whats-the-difference-between-thread-start-and-runnable-run) – peter_the_oak Mar 19 '15 at 16:32

4 Answers4

0

The method Thread.run() would execute the method in the current or main thread. Whereas the method Thread.start() would execute the logic in a separate thread.

More Information What's the difference between Thread start() and Runnable run()

Community
  • 1
  • 1
Ved Agarwal
  • 565
  • 3
  • 6
  • 14
0

If you call the run() method directly on your class, it will execute the code in the main thread. When you use the Thread.start() method a new thread is created. The JVM then calls your run() method when the thread is allowed to run.

Have a look at the Oracle documentation for this.

Erwin de Gier
  • 632
  • 7
  • 12
0

Thread.start() creates a new thread and calls runnable parallelly where as Thread.run() works as just a method call.i.e, no thread is created,So we mostly use Thread.start()

0
  1. Thread.start will create a new thread from the current running code and call Thread.run function.
  2. Thread.run will call this class's run method without creating a new thread.

Thread.java:

public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0 || this != me)
        throw new IllegalThreadStateException();
    group.add(this);
    start0();
    if (stopBeforeStart) {
        stop0(throwableFromStop);
    }
}
public void run() {
    if (target != null) {
        target.run();
    }
}

JDK Thread class: http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/5672a2be515a/src/share/classes/java/lang/Thread.java

chengpohi
  • 14,064
  • 1
  • 24
  • 42