forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurrentThredDemo.java
More file actions
79 lines (69 loc) · 1.95 KB
/
CurrentThredDemo.java
File metadata and controls
79 lines (69 loc) · 1.95 KB
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
73
74
75
76
77
78
79
package JavaBasic;/**
* @Classname CurrentThredDemo
* @Description TODO
* @Date 19-5-25 下午1:12
* @Created by mao<tianmao818@qq.com>
*/
public class CurrentThredDemo {
public static void main(String[] args){
Thread t=Thread.currentThread();
System.out.println("current thread:"+t);
t.setName("TIAN MAO");
System.out.println("After name change:"+t);
NewThread tt=new NewThread();
tt.start();
new NewThread_1();
try{
for(int i=0;i<5;i++){
System.out.println("main"+i);
Thread.sleep(1000);
}
}catch (InterruptedException e){
System.out.println("interrupted");
}
System.out.println("Main Thread exiting...");
}
}
//不重载Thread的其他方法的时候,使用Runnable
class NewThread implements Runnable{
Thread t;
NewThread(){
t=new Thread(this,"demo thread");
System.out.println("child thread"+t);
// 建立新的线程后,并不会直接运行,直到调用了start方法
// t.start();
}
public void start(){
t.start();
}
public void run(){
try{
for(int i=0;i<5;i++){
System.out.println("child 1:"+i);
Thread.sleep(1000);
}
}catch (InterruptedException e){
System.out.println("interrupted");
}
System.out.println("exit child 1 thread...");
}
}
class NewThread_1 extends Thread{
NewThread_1(){
super("Demo Thread");
System.out.println("children"+this);
start();
}
//需要被重载!!!
public void run(){
try{
for(int i=0;i<5;i++){
System.out.println("child 2:"+i);
Thread.sleep(1000);
}
}catch (InterruptedException e){
System.out.println("interrupted");
}
System.out.println("exit child 2 thread...");
}
}