黑马程序员技术交流社区
标题:
打印结果为什么是thread,有点没听明白?
[打印本页]
作者:
王竞
时间:
2014-3-19 17:08
标题:
打印结果为什么是thread,有点没听明白?
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable---" + Thread.currentThread().getName());
}
}
}) {
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread---" + Thread.currentThread().getName());
}
};
}.start();
作者:
青木郎
时间:
2014-3-19 18:17
因为你只创建一个线程,实现Runnable()接口的线程没有调用怎么可能打印,你只调用了thread的run()方法并start()
作者:
leon_hm
时间:
2014-3-19 21:10
楼主,我觉得你这种写法是即实现了Thread的子类又实现了Runnable接口。
但是肯定只会执行一种run()方法。从执行的结果来看是执行了Thread子类的方法。
我觉得类似下面这种写法
package Test;
public class TestMain {
public static void main(String[] args) {
/*
* String str=" main"; str = str.substring(1); //通过对象调用 //str =
* substring(1); 这样直接调用是不行的 System.out.println(str);
*/
/*
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable---"
+ Thread.currentThread().getName());
}
}
}) {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread---"
+ Thread.currentThread().getName());
}
};
}.start();
*/
new TestThread().start();
}
}
class TestThread extends Thread implements Runnable
{
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread---"
+ Thread.currentThread().getName());
}
};
}
复制代码
作者:
王竞
时间:
2014-3-19 23:14
leon_hm 发表于 2014-3-19 21:10
楼主,我觉得你这种写法是即实现了Thread的子类又实现了Runnable接口。
但是肯定只会执行一种run()方法。 ...
恩恩,我想明白了,谢谢。因为这里即实现了Thread的子类,又实现了Runnable接口的话,thread去调用start方法,start会先去子类找有没有run方法,如果找到,则使用子类的run方法,如果没有则到父类去找,应该选用实现Runnable接口的方法,因为这样更能体现面向接口编程的实现,更能体现面向对象。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2