-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadInfo.java
More file actions
89 lines (79 loc) · 2.78 KB
/
ThreadInfo.java
File metadata and controls
89 lines (79 loc) · 2.78 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
80
81
82
83
84
85
86
87
88
89
package cn.ucaner.core.thread;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @Package:cn.ucaner.core.thread
* @ClassName:ThreadInfo
* @Description: <p> 描述:线程优先级案例</p>
* @Author: - bysocket
* @CreatTime:2018年4月5日 下午1:07:37
* @Modify By:
* @ModifyTime: 2018年4月5日
* @Modify marker:
* @version V1.0
*/
public class ThreadInfo {
public static void main(String[] args) {
Thread threads[] = new Thread[10];
Thread.State status[] = new Thread.State[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(new Calculator(i));
if ((i % 2) == 0) {
threads[i].setPriority(Thread.MAX_PRIORITY);
} else {
threads[i].setPriority(Thread.MIN_PRIORITY);
}
// threads[i].setName("");
}
try {
// 将线程的信息写入log文件
FileWriter fw = new FileWriter(".\\log.txt");
PrintWriter pw = new PrintWriter(fw);
for (int i = 0; i <10 ;i++) {
pw.println("Main: Status of Thread " + i + " : "
+ threads[i].getState());
status[i] = threads[i].getState();
}
// 启动线程
for (int i = 0; i < 10 ;i++)
threads[i].start();
boolean finish = false;
while (!finish) {
for(int i = 0;i < 10 ;i++) {
if (threads[i].getState() != status[i]) {
writeThreadInfo(pw,threads[i],status[i]);
status[i] = threads[i].getState();
}
}
finish = true;
for (int i = 0;i < 10 ;i++) {
finish = finish && (threads[i].getState() == Thread.State.TERMINATED);//中断
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State status) {
pw.printf("Main: Id %d - $s\n",thread.getId(),thread.getName());
pw.printf("Main: Priority: %d\n",thread.getPriority());
pw.printf("Main: OldState: %s\n",status);
pw.printf("Main: New State: %s\n",thread.getState());
pw.printf("*****************************************\n");
}
}
class Calculator implements Runnable {
private int number;
public Calculator(int number) {
this.number = number;
}
@Override
public void run() {
for (int i = 0;i <=10; i++) {
System.out.printf("%s: %d * %d = %d\n",
Thread.currentThread().getName(),
number, i, i * number);
}
}
}