1. 程式人生 > >java 多執行緒基礎之一:多執行緒建立,執行,狀態管理

java 多執行緒基礎之一:多執行緒建立,執行,狀態管理



import java.lang.Thread.State;

public class Calculator implements Runnable {
    private int number;

    public Calculator(int number) {
        this.number=number;
    }    

    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);
        }
    }
    
    public static void main(String[] args) {
        System.out.printf("Minimum Priority: %s\n",Thread.MIN_PRIORITY);
        System.out.printf("Normal Priority: %s\n",Thread.NORM_PRIORITY);
        System.out.printf("Maximun Priority: %s\n",Thread.MAX_PRIORITY);
        
        Thread threads[];
        Thread.State status[];
        
        //發起10個執行緒,5個最高優先順序,5個最低優先順序,並設定執行緒的名字
        threads=new Thread[10];
        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+"執行緒");
        }
        
        
        // Wait for the finalization of the threads. Meanwhile, 
        // write the status of those threads in a file
        
        try {
            
            for (int i=0; i<10; i++){
                System.out.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(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);
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  列印執行緒狀態
     * @param thread : Thread 
     * @param state : Old state of the thread
     */
    private static void writeThreadInfo(Thread thread, State state) {
        System.out.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
        System.out.printf("Main : Priority: %d\n",thread.getPriority());
        System.out.printf("Main : Old State: %s\n",state);
        System.out.printf("Main : New State: %s\n",thread.getState());
        System.out.println("Main : ************************************\n");
    }
}