Java线程状态

参考文章:http://schnell18.iteye.com/blog/2187014
Thread类有一些保存信息的属性,这些属性可以用来标识线程,显示线程的状态或者控制线程的优先级。
ID:保存了线程的唯一表示符。
Name:保存了线程名称
Priority:保存了线程对象的优先级。线程的优先级是从1到10,其中1是最低优先级;10是最高优先级。
Status:保存了线程的状态。在Java中,线程的状态有6种:new、runnable、blocked、waiting、time waiting或者terminated

Java线程状态_第1张图片

Main.java

package org.lf.demo2;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.State;

public class Main {
    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("Thread "+i) ;
        }
        FileWriter file = null;
        try {
            file = new FileWriter(".\\data\\log.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //PrintWriter能够实现自动刷新
        PrintWriter pw = new PrintWriter(file,true) ;  
        for(int i=0;i<10;i++){
            pw.println("Main : Status of Thread "+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()==State.TERMINATED) ;
            }
        }
    }
    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 : ***********************************************\n") ;
    }
}

Calculator.java

package org.lf.demo2;

public class Calculator implements Runnable{
    private int number ;
    public Calculator(int number){
        this.number = number ;
    }
    @Override
    public void run() {
        for(int i=1;i<=10;i++){
            System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);
        }
    }

}

你可能感兴趣的:(java,线程)