通过这段代码可以了解线程各个阶段的状态:
package Test;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.State;
public class MyTest {
final private static int threadNum = 10;
public static void main(String[] args){
Thread threads[] = new Thread[10];
PrintWriter pw = null;
Thread.State status[] = new Thread.State[10];
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter("log.txt");
pw = new PrintWriter(fileWriter);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < threadNum; i++) {
Caculator caculator = new Caculator(i);
threads[i] = new Thread(caculator);
if (i%2 == 0 ) {
threads[i].setPriority(Thread.MAX_PRIORITY);
}
else {
threads[i].setPriority(Thread.MIN_PRIORITY);
}
threads[i].setName("thread"+i);
}
for (int i=0; i<threadNum; i++){
pw.println("Main : Status of Thread "+i+" : " +threads[i].getState());
status[i]=threads[i].getState();
threads[i].start();
}
boolean finish=false;
while (!finish) {
for (int i=0; i<threadNum; 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()==State.TERMINATED);
}
}
pw.close();
try {
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {
pw.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
pw.printf("Main : Priority: %d\n",thread.getPriority());
pw.printf("Main : Old State: %s\n",state);
pw.printf("Main : New State: %s\n",thread.getState());
pw.printf("Main : ************************************\n");
}
}
线程类:
package Test;
public class Caculator implements Runnable{
private int number;
public Caculator(){
number = 0;
}
public Caculator(int num){
number = num;
}
public void run() {
for(int i=0; i<10;++i){
System.out.printf("i=%d,thread:%s.\n",i,Thread.currentThread().getName());
}
}
}