重写线程类start()方法

无论何时重写start()方法,我们的start()方法都会像普通方法调用一样执行,并且不会创建新线程。我们可以重写Thread类的start/run方法,因为它不是final。但是 不建议重写start()方法 ,否则会破坏多线程概念。

null

// Java program illustrate the concept of
// overriding of start() method
class Bishal extends Thread {
public void start()
{
System.out.println( "Start Method" );
}
public void run()
{
System.out.println( "Run Method" );
}
} class Geeks {
public static void main(String[] args)
{
Bishal thread = new Bishal();
thread.start();
System.out.println( "Main Method" );
}
}


输出:

Start Method
Main Method

注: 在上面的程序中,当我们通过Bishal类的对象调用start()方法时,将不会创建任何线程,所有函数都只由主线程完成。

JVM为上述程序提供的运行时堆栈: 图片[1]-重写线程类start()方法-yiteyi-C++库

当我们在线程上调用start()方法时,它会在内部用新创建的线程调用run()方法。所以,如果我们重写start()方法,在我们编写调用run()方法的代码之前,不会调用run()方法。 另一个例子:

class GThread extends Thread
{
public void run()
{
System.out.println( "GThread: run()" );
}
public void start()
{
System.out.println( "GThread: start()" );
}
}
class GRunnable implements Runnable
{
public void run()
{
System.out.println( "GRunnable: run()" );
}
public void start()
{
System.out.println( "GRunnable: start()" );
}
}
public class MyTest
{
public static void main(String args[])
{
GThread gt  = new GThread();
GRunnable gr = new GRunnable();
Thread thread  = new Thread(gr);
gt.start();
thread.start();
}
}


输出:

GThread: start()
GRunnable: run()

当GThread。调用start(),输出为:“GThread:start()”。当我们打电话时,线程。新线程将调用runnable的run()方法,我们将得到“GRunnable:run()”消息。

本文由 比沙尔·库马尔·杜比 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享