class MyThread extends Thread {
MyThread(){}
MyThread(Runnable r) {super(r);}
public void run() { System.out.print("Inside Thread");}
}class MyRunnable implements Runnable {
public void run() {System.out.print("Inside runnable");}
}class Test{
public static void main(String[] args){
new MyThread().start();
new MyThread(new MyRunnable()).start();
}
}
输出为什么是2个Inside Thread
MyThread(){}
MyThread(Runnable r) {super(r);}
public void run() { System.out.print("Inside Thread");}
}class MyRunnable implements Runnable {
public void run() {System.out.print("Inside runnable");}
}class Test{
public static void main(String[] args){
new MyThread().start();
new MyThread(new MyRunnable()).start();
}
}
输出为什么是2个Inside Thread
第二个其实和第一个一样,只不过你被MyThread(Runnable r) {super(r);}迷惑了;
new MyThread(new MyRunnable()).start();这里调用的还是MyThread的run方法。
如果该句换成new Thread(new MyRunnable()).start();就会输出Inside runnable。
MyThread(){}
MyThread(Runnable r) {super(r);}
public void run() { System.out.println("Inside Thread");}
}class MyRunnable implements Runnable {
public void run() {System.out.println("Inside runnable");}
}class Test{
public static void main(String[] args){
MyRunnable mr=null;
mr=new MyRunnable();
new MyThread().start();
new MyThread(mr).start(); //因为MyThread有了run方法 Thread thread = new Thread(mr);//没有方法,就运行mr.run()
thread.start();
}
}设计Runnable接口的目的是为希望在活动时执行代码的对象提供一个公共协议。Runnable 为非 Thread 子类的类提供了一种激活方式。通过实例化某个 Thread 实例并将自身作为运行目标,就可以运行实现 Runnable 的类而无需创建 Thread 的子类。Thread 是已经实现Runnable 接口的了