1.在Thread子类覆盖的run方法中编写运行代码
Thread t1 = new Thread(){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1:"+Thread.currentThread().getName());
//this代表run方法所在的对象,即t1
//System.out.println("t1:"+this.getName());
}
}
};
t1.start();
不能在run方法声明上抛出InterruptedException异常,以便省略run方法内部对Thread.sleep()语句的try…catch处理2.在传递给Thread对象的Runnable对象的run方法中编写代码
Thread t2 = new Thread(new Runnable(){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2:"+Thread.currentThread().getName());
}
}
});
t2.start();
问:为什么都是采用Runnable这种方式创建线程?
答:体现了面向对象性, 因为run()方法在Runnable对象里面和Thread对象解耦
3.看如下代码,会输出什么结果?
new Thread(new Runnable(){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable:"+Thread.currentThread().getName());
}
}
}){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread:"+Thread.currentThread().getName());
}
}
}.start();
输出结果:
Thread:Thread-2
原因是:只会运行子类的run()方法,因为根据源码是先看子类有没有run()方法, 如果有,就覆盖父类的run()方法。所以执行子类的run()方法,如果子类没有run()方法,就运行构造器里的Runnable()的run()方法。