一. 传统线程创建方法
1. 覆盖Thread子类的run方法中编写具体代码
2. 在传递给Thread的Runnable对象的run方法中编写具体代码
二. 实现代码
public class TraditionalThread {
public static void main(String[] args) {
// 方法1:直接new一个Thread的子类,让子类run方法覆盖父类的run方法
Thread thread1 = new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread1.start();
// 方法2:给Thread类传一个实现了Runnable接口的类
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread2.start();
}
}
小知识:
1. new Thread(){
} 这种写法其实是创建了Thread的子类
2. new Thread(new Runnable(){}){
} 传递给Thread的参数其实是Runnable的实现类对象
三. 一个典型例子:
请问下面的类是执行Runnable中的run方法还是Thread子类的方法?
public class Test {
public static void main(String[] args) {
// 下面的代码将会运行Thread子类的run方法而不会运行runnable中的run方法
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable:" + Thread.currentThread().getName());
}
}
}) {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread:" + Thread.currentThread().getName());
}
}
}.start();
}
/**
* Thread 类中的run方法
* private Runnable target;
*
* public void run() {
* if (target != null) {
* target.run();
* }
* }
**/
}
答案是执行Thread子类的run方法, 因为它覆盖了父类的run方法,根本就不会执行到runnable的方法,即target.run()