你何时会调用java的thread.run()而不是thread.start()?

时间:2022-04-27 00:30:01

When would you call Java's thread.run() instead of thread.start()?

你何时会调用Java的thread.run()而不是thread.start()?

14 个解决方案

#1


109  

You might want to call run() in a particular unit test that is concerned strictly with functionality and not with concurrency.

您可能希望在特定单元测试中调用run(),该测试严格关注功能而不是并发。

#2


93  

Never. Calling run() directly just executes the code synchronously (in the same thread), just like a normal method call.

决不。直接调用run()只是同步执行代码(在同一个线程中),就像普通的方法调用一样。

#3


27  

Taken form the Code Style Java threads FAQ:

采用代码样式Java线程FAQ:

Q: What's the difference between a thread's start() and run() methods?

问:线程的start()和run()方法有什么区别?

A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

答:Thread类中的单独start()和run()方法提供了两种创建线程程序的方法。 start()方法开始执行新线程并调用run()方法。 start()方法立即返回,新线程通常会继续,直到run()方法返回。

The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Thread类的run()方法不执行任何操作,因此子类应该使用代码覆盖该方法以在第二个线程中执行。如果使用Runnable参数实例化Thread,则线程的run()方法将在新线程中执行Runnable对象的run()方法。

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

根据线程程序的性质,直接调用Thread run()方法可以提供与通过start()方法调用相同的输出,但在后一种情况下,代码实际上是在新线程中执行的。

#4


23  

Executing thread.run() doesn't create a new Thread in which your code gets executed. It just executes the code in the current Thread from which the thread.run() code is invoked.

执行thread.run()不会创建一个执行代码的新线程。它只执行当前Thread中的代码,从中调用thread.run()代码。

Executing thread.start() creates a new OS level thread wherein the run() method gets called.

执行thread.start()会创建一个新的OS级别线程,其中run()方法被调用。

In essence:

在本质上:

Single Threaded programming → Directly calling the run() method

单线程编程→直接调用run()方法

Multi Threaded programming → Calling the start() method

多线程编程→调用start()方法

Moreover, as other's have mentioned, 'testing' seems to be the only advisable case wherein you may invoke run() directly from your code.

此外,正如其他人所提到的,“测试”似乎是唯一可行的情况,您可以直接从代码中调用run()。

#5


13  

This has already been alluded to, but just to be clear: creating a new Thread object only to call it's run() method is needlessly expensive and should be a major red flag. It would be a much better, more decoupled design to create a Runnable impl and either (a) call it's run() method directly if that's the desired behavior, or (b) construct a new Thread with that Runnable and start the Thread.

这已经被提到了,但只是要明确:创建一个新的Thread对象只是为了调用它的run()方法是不必要的昂贵,应该是一个主要的红旗。创建一个Runnable impl并且(a)直接调用它的run()方法(如果这是所需的行为),或者(b)用Runnable构造一个新的Thread并启动Thread,这将是一个更好,更分离的设计。

Better yet, for even more decoupling, check out the Executor interface and framework in JDK 5 and newer. This allows you, in a nutshell, to decouple task execution (the Runnable instance) from how it is executed (the Executor implementation, which might execute the Runnable in the current Thread, in a new Thread, using an existing Thread from a pool, and whatnot).

更好的是,为了进一步解耦,请查看JDK 5及更高版本中的Executor接口和框架。简而言之,这允许您将任务执行(Runnable实例)与其执行方式(Executor实现,可能在新线程中执行当前线程中的Runnable,使用池中的现有线程)分离,什么)。

#6


9  

Call thread.start(), it will in turn call thread.run(). Can't think of a case when you would want to bypass thread.start() and go directly to thread.run()

调用thread.start(),它将依次调用thread.run()。当你想要绕过thread.start()并直接转到thread.run()时,想不到一个案例

#7


9  

The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

Thread类中的单独start()和run()方法提供了两种创建线程程序的方法。 start()方法开始执行新线程并调用run()方法。 start()方法立即返回,新线程通常会继续,直到run()方法返回。

The Thread class’ run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread’s run() method executes the run() method of the Runnable object in the new thread instead.

Thread类的run()方法不执行任何操作,因此子类应该使用代码覆盖该方法以在第二个线程中执行。如果使用Runnable参数实例化Thread,则线程的run()方法将在新线程中执行Runnable对象的run()方法。

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

根据线程程序的性质,直接调用Thread run()方法可以提供与通过start()方法调用相同的输出,但在后一种情况下,代码实际上是在新线程中执行的。

reference

参考

#8


7  

If the Question was - "why the thread start method is called instead of run method directly" then i have answered with an example code below. Hope that clarifies. In the Example below:

如果问题是 - “为什么直接调用线程启动方法而不是直接运行方法”,那么我已经回答了下面的示例代码。希望澄清一下。在下面的示例中:

/*
By calling t1.start(), 
we are getting the main calling thread returned immediately 
after the t1.start() called and is ready to proceed for other 
operations.And the thread t1 starts executing the run method of the object r. 
Hence the the output will be:

      I am the main thread , i created thread t1 and had it execute run method, which is currently looping from 0 to 1000000

      I am done executing run method of testThread

*/


/* If we call t1.run() instead of t1.start(), (just replace t1.start() with t1.run() in the code for testing)
 its like a regular method call and the main thread will not return until the run method completes, 
 hence the output will be:

         I am done executing run method of testThread

         I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000

*/


class testThread implements Runnable{

 public void run()
 {
     for(int i=0;i<1000000;i++){} //a simple delay block to clarify.

     System.out.println("I am done executing run method of testThread");

 }  
}

public class mainClass{

   public static void main(String [] args)
    {
          testThread r = new testThread();
          Thread t1 = new Thread(r);
          t1.start();  /* Question is: can we call instead t1.run() */  
          System.out.println("I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000");

    }
}

#9


5  

When you want it to run synchronously. Calling the run method won't actually give you multi-threading. The start method creates a new thread which calls the run method.

当您希望它同步运行时。调用run方法实际上不会给你多线程。 start方法创建一个调用run方法的新线程。

#10


3  

If you want to execute the contents of run() like you would of any other method. Not to start a thread, of course.

如果你想像执行任何其他方法那样执行run()的内容。当然不要开始一个帖子。

#11


3  

Assuming that you know the start and run method usage i.e. synchronous vs. asynchronous; run method can be used just to test the functionality.

假设你知道启动和运行方法的使用,即同步与异步; run方法只能用于测试功能。

Plus in some circumstances, the same thread class can be used in two different places with synch and asynch functionality requirements by having two different objects with one's run method and other's start method being invoked.

此外,在某些情况下,通过使用一个run方法和另一个start方法调用两个不同的对象,可以在具有synch和asynch功能要求的两个不同位置使用相同的线程类。

#12


2  

At least in the JVM 1.6., there's a bit of checking and run is called natively:

至少在JVM 1.6。中,有一些检查和运行被称为本机:

 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)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
        stop0(throwableFromStop);
    }
    }

    private native void start0();

#13


2  

Just a note to the above great comments: sometimes your write a multi-thread code which uses "start" method to run different threads. You will find it much easier if you use "run" (instead of "start) for debugging since it makes the code to run synchronously and debugging it much easier.

只需注意以上很棒的评论:有时你会编写一个多线程代码,它使用“start”方法来运行不同的线程。如果使用“run”(而不是“start”)进行调试,你会发现它更容易,因为它使代码同步运行并更容易调试。

#14


-1  

public class TestClass implements Runnable {
    public static void main(String[] args) {
        TestClass tc = new TestClass();

        Thread t1 = new Thread(tc);
        System.out.println("Before Starting Thread " + Thread.currentThread().hashCode());
        t1.start();
        System.out.println("After Starting Thread " + Thread.currentThread().hashCode());
    }

    @Override
    public void run() {
        System.out.println("TestClass Run method is  Running with thread " + Thread.currentThread().hashCode());        
    }
}

#1


109  

You might want to call run() in a particular unit test that is concerned strictly with functionality and not with concurrency.

您可能希望在特定单元测试中调用run(),该测试严格关注功能而不是并发。

#2


93  

Never. Calling run() directly just executes the code synchronously (in the same thread), just like a normal method call.

决不。直接调用run()只是同步执行代码(在同一个线程中),就像普通的方法调用一样。

#3


27  

Taken form the Code Style Java threads FAQ:

采用代码样式Java线程FAQ:

Q: What's the difference between a thread's start() and run() methods?

问:线程的start()和run()方法有什么区别?

A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

答:Thread类中的单独start()和run()方法提供了两种创建线程程序的方法。 start()方法开始执行新线程并调用run()方法。 start()方法立即返回,新线程通常会继续,直到run()方法返回。

The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Thread类的run()方法不执行任何操作,因此子类应该使用代码覆盖该方法以在第二个线程中执行。如果使用Runnable参数实例化Thread,则线程的run()方法将在新线程中执行Runnable对象的run()方法。

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

根据线程程序的性质,直接调用Thread run()方法可以提供与通过start()方法调用相同的输出,但在后一种情况下,代码实际上是在新线程中执行的。

#4


23  

Executing thread.run() doesn't create a new Thread in which your code gets executed. It just executes the code in the current Thread from which the thread.run() code is invoked.

执行thread.run()不会创建一个执行代码的新线程。它只执行当前Thread中的代码,从中调用thread.run()代码。

Executing thread.start() creates a new OS level thread wherein the run() method gets called.

执行thread.start()会创建一个新的OS级别线程,其中run()方法被调用。

In essence:

在本质上:

Single Threaded programming → Directly calling the run() method

单线程编程→直接调用run()方法

Multi Threaded programming → Calling the start() method

多线程编程→调用start()方法

Moreover, as other's have mentioned, 'testing' seems to be the only advisable case wherein you may invoke run() directly from your code.

此外,正如其他人所提到的,“测试”似乎是唯一可行的情况,您可以直接从代码中调用run()。

#5


13  

This has already been alluded to, but just to be clear: creating a new Thread object only to call it's run() method is needlessly expensive and should be a major red flag. It would be a much better, more decoupled design to create a Runnable impl and either (a) call it's run() method directly if that's the desired behavior, or (b) construct a new Thread with that Runnable and start the Thread.

这已经被提到了,但只是要明确:创建一个新的Thread对象只是为了调用它的run()方法是不必要的昂贵,应该是一个主要的红旗。创建一个Runnable impl并且(a)直接调用它的run()方法(如果这是所需的行为),或者(b)用Runnable构造一个新的Thread并启动Thread,这将是一个更好,更分离的设计。

Better yet, for even more decoupling, check out the Executor interface and framework in JDK 5 and newer. This allows you, in a nutshell, to decouple task execution (the Runnable instance) from how it is executed (the Executor implementation, which might execute the Runnable in the current Thread, in a new Thread, using an existing Thread from a pool, and whatnot).

更好的是,为了进一步解耦,请查看JDK 5及更高版本中的Executor接口和框架。简而言之,这允许您将任务执行(Runnable实例)与其执行方式(Executor实现,可能在新线程中执行当前线程中的Runnable,使用池中的现有线程)分离,什么)。

#6


9  

Call thread.start(), it will in turn call thread.run(). Can't think of a case when you would want to bypass thread.start() and go directly to thread.run()

调用thread.start(),它将依次调用thread.run()。当你想要绕过thread.start()并直接转到thread.run()时,想不到一个案例

#7


9  

The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

Thread类中的单独start()和run()方法提供了两种创建线程程序的方法。 start()方法开始执行新线程并调用run()方法。 start()方法立即返回,新线程通常会继续,直到run()方法返回。

The Thread class’ run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread’s run() method executes the run() method of the Runnable object in the new thread instead.

Thread类的run()方法不执行任何操作,因此子类应该使用代码覆盖该方法以在第二个线程中执行。如果使用Runnable参数实例化Thread,则线程的run()方法将在新线程中执行Runnable对象的run()方法。

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

根据线程程序的性质,直接调用Thread run()方法可以提供与通过start()方法调用相同的输出,但在后一种情况下,代码实际上是在新线程中执行的。

reference

参考

#8


7  

If the Question was - "why the thread start method is called instead of run method directly" then i have answered with an example code below. Hope that clarifies. In the Example below:

如果问题是 - “为什么直接调用线程启动方法而不是直接运行方法”,那么我已经回答了下面的示例代码。希望澄清一下。在下面的示例中:

/*
By calling t1.start(), 
we are getting the main calling thread returned immediately 
after the t1.start() called and is ready to proceed for other 
operations.And the thread t1 starts executing the run method of the object r. 
Hence the the output will be:

      I am the main thread , i created thread t1 and had it execute run method, which is currently looping from 0 to 1000000

      I am done executing run method of testThread

*/


/* If we call t1.run() instead of t1.start(), (just replace t1.start() with t1.run() in the code for testing)
 its like a regular method call and the main thread will not return until the run method completes, 
 hence the output will be:

         I am done executing run method of testThread

         I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000

*/


class testThread implements Runnable{

 public void run()
 {
     for(int i=0;i<1000000;i++){} //a simple delay block to clarify.

     System.out.println("I am done executing run method of testThread");

 }  
}

public class mainClass{

   public static void main(String [] args)
    {
          testThread r = new testThread();
          Thread t1 = new Thread(r);
          t1.start();  /* Question is: can we call instead t1.run() */  
          System.out.println("I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000");

    }
}

#9


5  

When you want it to run synchronously. Calling the run method won't actually give you multi-threading. The start method creates a new thread which calls the run method.

当您希望它同步运行时。调用run方法实际上不会给你多线程。 start方法创建一个调用run方法的新线程。

#10


3  

If you want to execute the contents of run() like you would of any other method. Not to start a thread, of course.

如果你想像执行任何其他方法那样执行run()的内容。当然不要开始一个帖子。

#11


3  

Assuming that you know the start and run method usage i.e. synchronous vs. asynchronous; run method can be used just to test the functionality.

假设你知道启动和运行方法的使用,即同步与异步; run方法只能用于测试功能。

Plus in some circumstances, the same thread class can be used in two different places with synch and asynch functionality requirements by having two different objects with one's run method and other's start method being invoked.

此外,在某些情况下,通过使用一个run方法和另一个start方法调用两个不同的对象,可以在具有synch和asynch功能要求的两个不同位置使用相同的线程类。

#12


2  

At least in the JVM 1.6., there's a bit of checking and run is called natively:

至少在JVM 1.6。中,有一些检查和运行被称为本机:

 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)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
        stop0(throwableFromStop);
    }
    }

    private native void start0();

#13


2  

Just a note to the above great comments: sometimes your write a multi-thread code which uses "start" method to run different threads. You will find it much easier if you use "run" (instead of "start) for debugging since it makes the code to run synchronously and debugging it much easier.

只需注意以上很棒的评论:有时你会编写一个多线程代码,它使用“start”方法来运行不同的线程。如果使用“run”(而不是“start”)进行调试,你会发现它更容易,因为它使代码同步运行并更容易调试。

#14


-1  

public class TestClass implements Runnable {
    public static void main(String[] args) {
        TestClass tc = new TestClass();

        Thread t1 = new Thread(tc);
        System.out.println("Before Starting Thread " + Thread.currentThread().hashCode());
        t1.start();
        System.out.println("After Starting Thread " + Thread.currentThread().hashCode());
    }

    @Override
    public void run() {
        System.out.println("TestClass Run method is  Running with thread " + Thread.currentThread().hashCode());        
    }
}