|
| 1 | +package org.javacore.thread; |
| 2 | + |
| 3 | + |
| 4 | +import java.io.FileWriter; |
| 5 | +import java.io.IOException; |
| 6 | +import java.io.PrintWriter; |
| 7 | + |
| 8 | +/** |
| 9 | + * Created by bysocket on 16/2/24. |
| 10 | + */ |
| 11 | +public class ThreadInfo { |
| 12 | + public static void main(String[] args) { |
| 13 | + Thread threads[] = new Thread[10]; |
| 14 | + Thread.State status[] = new Thread.State[10]; |
| 15 | + for (int i = 0; i < 10; i++) { |
| 16 | + threads[i] = new Thread(new Calculator(i)); |
| 17 | + if ((i % 2) == 0) { |
| 18 | + threads[i].setPriority(Thread.MAX_PRIORITY); |
| 19 | + } else { |
| 20 | + threads[i].setPriority(Thread.MIN_PRIORITY); |
| 21 | + } |
| 22 | +// threads[i].setName(""); |
| 23 | + } |
| 24 | + |
| 25 | + try { |
| 26 | + // 将线程的信息写入log文件 |
| 27 | + FileWriter fw = new FileWriter(".\\log.txt"); |
| 28 | + PrintWriter pw = new PrintWriter(fw); |
| 29 | + |
| 30 | + for (int i = 0; i <10 ;i++) { |
| 31 | + pw.println("Main: Status of Thread " + i + " : " |
| 32 | + + threads[i].getState()); |
| 33 | + status[i] = threads[i].getState(); |
| 34 | + } |
| 35 | + |
| 36 | + // 启动线程 |
| 37 | + for (int i = 0; i < 10 ;i++) |
| 38 | + threads[i].start(); |
| 39 | + |
| 40 | + boolean finish = false; |
| 41 | + while (!finish) { |
| 42 | + for(int i = 0;i < 10 ;i++) { |
| 43 | + if (threads[i].getState() != status[i]) { |
| 44 | + writeThreadInfo(pw,threads[i],status[i]); |
| 45 | + status[i] = threads[i].getState(); |
| 46 | + } |
| 47 | + } |
| 48 | + finish = true; |
| 49 | + for (int i = 0;i < 10 ;i++) { |
| 50 | + finish = finish && (threads[i].getState() == Thread.State.TERMINATED);//中断 |
| 51 | + } |
| 52 | + } |
| 53 | + } catch (IOException e) { |
| 54 | + e.printStackTrace(); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State status) { |
| 59 | + pw.printf("Main: Id %d - $s\n",thread.getId(),thread.getName()); |
| 60 | + pw.printf("Main: Priority: %d\n",thread.getPriority()); |
| 61 | + pw.printf("Main: OldState: %s\n",status); |
| 62 | + pw.printf("Main: New State: %s\n",thread.getState()); |
| 63 | + pw.printf("*****************************************\n"); |
| 64 | + } |
| 65 | +} |
| 66 | +class Calculator implements Runnable { |
| 67 | + |
| 68 | + private int number; |
| 69 | + |
| 70 | + public Calculator(int number) { |
| 71 | + this.number = number; |
| 72 | + } |
| 73 | + |
| 74 | + @Override |
| 75 | + public void run() { |
| 76 | + for (int i = 0;i <=10; i++) { |
| 77 | + System.out.printf("%s: %d * %d = %d\n", |
| 78 | + Thread.currentThread().getName(), |
| 79 | + number, i, i * number); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments