调用类的run方法(由线程类扩展或由runnable接口实现)? [英] Calling run method of classes(either extended by thread class or implemented by runnable interface)?
本文介绍了调用类的run方法(由线程类扩展或由runnable接口实现)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class MyThread extends 主题
{
MyThread(Runnable r)
{
super (r);
}
public void run()
{
SOP( 我的线程运行。);
}
}
class MyRunnable实现Runnable
{
public void run()
{
SOP(我的runnable run。);
}
}
公共类MyMain
{
public static void main(String [ ] arg){
MyThread obj = new MyThread(new MyRunnable());
obj.start();}
}
将调用哪个run方法,为什么???
解决方案
无。
- 您的代码无效( SOP ???)
-Runnable
是一个接口(implements
不是extends
- 除非MyRunnable
当然也是一个接口。)
,主要原因是类MyMain
将无法运行,因为它没有主要功能。
但是当你修改它是一个有效的代码(有3个单独的类!):
< pre lang =java> public class MyMain {
public static MyThread oThread = new MyThread( new MyRunnable());
public static void main( String [] args){
oThread.start();
}
}
class MyThread extends 线程{
MyThread(Runnable r){
super ( R);
}
@覆盖
public void run(){
System.out.println( 我的线程运行。);
}
}
class MyRunnable < span class =code-keyword> implements Runnable {
@ Override
public void run(){
System.out.print( < span class =code-string>我的runnable运行。);
}
}
线程
正在运行。为什么?
检查代码 - 它是覆盖
run()
方法可运行
。
如果从Thread中删除run方法,runnable的run方法就可以运行了。
编辑:在代码突出显示的情况下稍微挣扎......
class MyThread extends Thread
{
MyThread(Runnable r)
{
super(r);
}
public void run()
{
SOP("my thread runs.");
}
}
class MyRunnable implements Runnable { public void run() { SOP("my runnable runs."); } }
public class MyMain { public static void main(String[] arg){ MyThread obj = new MyThread(new MyRunnable()); obj.start();} }
which run method will be called and why???
解决方案
none.
- your code is not valid (SOP???)
-Runnable
is an interface (implements
notextends
- unlessMyRunnable
is an Interface too, of course.)
and the main reason is that the classMyMain
will not run because it does not have main function.
BUT when you modify that to be a valid code (with 3 separate classes!):
public class MyMain { public static MyThread oThread = new MyThread(new MyRunnable()); public static void main(String[] args) { oThread.start(); } }
class MyThread extends Thread { MyThread(Runnable r) { super(r); } @Override public void run() { System.out.println("my thread runs."); } }
class MyRunnable implements Runnable { @Override public void run() { System.out.print("my runnable runs."); } }
TheThread
is running. Why?
Check the code - it''soverriding
therun()
method from theRunnable
.
If you remove the run method from the Thread the runnable''s run method is getting it''s chance to run.
EDIT: struggled a little with the code highlighting...
这篇关于调用类的run方法(由线程类扩展或由runnable接口实现)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文