class MyThread extends Thread{
public void run(){
System.out.println("MyThread: run()");
}
public void start(){
System.out.println("MyThread: start()");
}
}
class MyRunnable implements Runnable{
public void run(){
System.out.println("MyRunnable: run()");
}
public void start(){
System.out.println("MyRunnable: start()");
}
}
public class MyTest {
public static void main(String args[]){
MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();
}
}求解释为什么输出:F:\>java MyTest
MyThread: start()
MyRunnable: run()
public void run(){
System.out.println("MyThread: run()");
}
public void start(){
System.out.println("MyThread: start()");
}
}
class MyRunnable implements Runnable{
public void run(){
System.out.println("MyRunnable: run()");
}
public void start(){
System.out.println("MyRunnable: start()");
}
}
public class MyTest {
public static void main(String args[]){
MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();
}
}求解释为什么输出:F:\>java MyTest
MyThread: start()
MyRunnable: run()
解决方案 »
- 怎么让Iterator实现多个集合
- java中“”(双引号) 和''(单引号)的区别?
- JCreator无法编译项目
- 问个《Core Java 2》中一个多线程例题
- JAVA读写文件到底是字节还是字符形式
- 跪求进来看下。。。。
- [200分]急速求助啊,JAVA语言编程谁可以用"雅可比迭代法"和"高斯-赛德尔迭代法"求解方程组啊
- java+xml 如何设置xml的编码?
- 请问,这是什么问题(hello world)
- vj++打开Form1.java的时候,出现错误:"java.lang.IllegalAccessError: com/ms/wfc/util/Debug$Switch"
- 启动都出错!到底什么回事啊!
- Java面试题分享
public void run() {
if (target != null) {
target.run();
}
}
如果没传参数runnble,run()方法里什么也没执行。
如果传了参数执行 target 的 run()方法。
至于start()方法,没有用到target。
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 || this != me)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
也没什么顺序问题
这里牵扯的问题就如上边那位仁兄所说:一个是子类重写父类方法,重写后的start()显然是没有启动run()方法的能力的;二就是利用接口参数来构造一个线程的多态的展现,这里的MyRunnable只是作为一个参数,实际new的是一个Thread,所以thread的start()方法自然就是Thread类里那个用来启动线程的 start()方法
赞同此说法,但是
MyRunnable是线程,但线程没有启动,
再说第二个MyRunnable类,他不是线程,只是实现了线程需要的一个接口,而Thread线程类有它自己的start方法(它里面默认只调用run方法,),所以利用实现接口而得的线程thread掉用start方法,只看到类MyRunnalble中的run方法。所以执行结果是MyRunnable: run()