我们已经讨论过了 Java线程通常使用以下两种方法之一创建:(1)扩展线程类。(2) 实现Runnable 在这两种方法中,我们都重写run()函数,但我们通过调用start()函数来启动线程。那么我们为什么不直接调用被重写的run()函数呢?为什么总是调用start函数来执行线程? 调用函数时会发生什么? 调用函数时,将执行以下操作:
null
- 对参数进行评估。
- 一个新的堆栈框架被推入调用堆栈。
- 参数已初始化。
- 方法体被执行。
- 返回值,并从调用堆栈弹出当前堆栈帧。
start()的目的是为线程创建一个单独的调用堆栈。它创建一个单独的调用堆栈,然后JVM调用run()。 让我们看看如果我们不调用start()而直接调用run()会发生什么。我们已经修改了讨论的第一个程序 在这里 .
JAVA
// Java code to see that all threads are // pushed on same stack if we use run() // instead of start(). class ThreadTest extends Thread { public void run() { try { // Displaying the thread that is running System.out.println ( "Thread " + Thread.currentThread().getId() + " is running" ); } catch (Exception e) { // Throwing an exception System.out.println ( "Exception is caught" ); } } } // Main Class public class Main { public static void main(String[] args) { int n = 8 ; for ( int i= 0 ; i<n; i++) { ThreadTest object = new ThreadTest(); // start() is replaced with run() for // seeing the purpose of start object.run(); } } } |
输出:
Thread 1 is runningThread 1 is runningThread 1 is runningThread 1 is runningThread 1 is runningThread 1 is runningThread 1 is runningThread 1 is running
我们可以从上面的输出中看到,所有线程的ID都相同,因为我们直接调用了run()。调用start()的程序会打印不同的ID(请参阅 这 ) 参考资料:
- http://www.javatpoint.com/what-if-we-call-run()直接法
- http://www.leepoint.net/JavaBasics/methods/methods-25-calls.html
本文由 kp93 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END