众所周知创建线程主要有两种方式一种是继承Thread 类一种是实现Runnable接口
(1)Thread
Thread thread=new Thread(){
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();
```
(2)Runnable
Thread thread1=new Thread(new Runnable() {
public void run(){
while (true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
});
thread1.start();
那下面这种方式输出的是什么呢
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable"+Thread.currentThread().getName());
}
}){
public void run(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread"+Thread.currentThread().getName());
}
}.start();
}
“`
。。。。。。。。
输出的是 threadxxx
首先运行的是 start 方法 会去找 new Thread 中的run方法这里已经实现了run方法所以会直接执行。如果没有设置run方法则会去找父类中的run方法则会执行runnable中的run 方法
项目源码:https://github.com/haha174/thread-learning.git
文章地址:http://www.haha174.top/article/details/253945