1.传统两种方式实现线程
package com.qunar.thread;
public class TraditionalThread {
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
System.out.println(this.getName());
}
}
};
thread.start();
Thread thread2 = new Thread( new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
});
thread2.start();
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();
}
}
运行结果:
threadThread-2
Thread-1
Thread-0
Thread-0
threadThread-2
Thread-1
Thread-0
Thread-0
可以看出最后一个线程,虽然既有thread的run方法也有Runnable中的run方法,但是结果是运行的Thread中的,Thread首先会检查自己是否有run方法没有则调用Runnable对象的run方法