一. 传统线程创建方法
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()