传统创建线程的方式

传统创建线程的方式

  1. extends Thread
  2. implements Runnable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package me.qianlv;
public class TraditionalThread {
public static void main(String[] args) {
//创建线程的第一种方式
Thread thread1 = new Thread() {
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread 1:" + Thread.currentThread().getName());
}
}
};
thread1.start();
//创建线程的第二种方式
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread 2:" + Thread.currentThread().getName());
}
}
});
thread2.start();
//下面这种写法,究竟会执行哪个run方法呢?
Thread thread3 = new Thread(new Runnable(){
@Override
public void run(){
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread 3: Runnable " + Thread.currentThread().getName());
}
}
}){
@Override
public void run(){
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread 3: Thread " + Thread.currentThread().getName());
}
}
};
thread3.start();
}
}

输出结果:

1
2
3
thread 1:Thread-0
thread 2:Thread-1
thread 3: Thread Thread-2

对于第三种输出结果,利用Java的多态特性即可知道原因.new Thread(){}创建了 Thread 子类,所以在运行的时候,首先会查看子类是否有 run 方法,当有时,执行此子类的方法.

您的支持将鼓励我继续创作!