当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Calling Runnable's run() method directly on thread object

问题描述:

We cannot call Runnable's run() method directly on thread's object but according to the below program we are doing it without any compilation or Runtime errors.Why is it so?

public class ThreadCheck implements Runnable {

@Override

public void run() {

for (int i=0; i<10; ) {

System.out.println(++i);

}

}

public static void main(String[] args) {

Thread mythread = new Thread(new ThreadCheck());

mythread.run();

mythread.run();

mythread.start();

}

}

Output:

1

2

3

4

5

6

7

8

9

10

1

2

3

4

5

6

7

8

9

10

1

2

3

4

5

6

7

8

9

10

网友答案:

This will not have any compilation or run-time errors. But it also will not spawn new threads. It will execute the run() method in the current main thread.

refer what will happen if we directly call run method?

网友答案:

We can call Runnable's run() method directly on thread's object. But, when you call run() method from thread's object, the run() method will work as a normal method. When you call it, it doesn't create a new thread.

In this case the run() method will be treated as a normal method call. But when you call the start() method on the Thread object, then it automatically calls the run() method on a new thread in the JVM.

网友答案:

We cannot call Runnable's run() method directly on thread's object

That is not true. Your example proves that you can call it. But maybe it does not do what you think it does.

See Two thread which invokes wait and notify for a simple explanation of the relationship between the Thread class and the Runnable interface.

网友答案:

To create/spawn a custom new thread, two things are necessary:

  • Create a new Thread object (call it thread) with the argument as object reference of the custom thread (myThread in this case)

  • Call thread.start();

run() can be called directly, but the sequence of executions in the run method will not happen in a new thread! The sequence of executions will take place in the existing thread for the main method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: