Java線程優先級測試

 如果有什麼不好的地方,請大家多多指教...

  1. //注意,優先級並不能確保運行的次序,僅僅是看誰能佔有更多的CPU時間片  
  2. class Priority implements Runnable{  
  3.     Thread t1,t2,t3,notify;  
  4.       
  5.     Priority(){  
  6.         t1=new Thread(this);  
  7.         t1.setPriority(5);  
  8.         t2=new Thread(this);  
  9.         t2.setPriority(1);  
  10.         t3=new Thread(this);  
  11.         t3.setPriority(10);  
  12.         notify=new Thread(this);  
  13.     }  
  14.       
  15.     public void notice(){  
  16.         synchronized(this){  
  17.             notify();  
  18.         }     
  19.     }  
  20.       
  21.     public synchronized void run(){  
  22.         if(Thread.currentThread()==t1){  
  23.             System.out.println("t1");  
  24.             try{  
  25.                 synchronized(this){  
  26.                     wait(); //交出鎖並阻塞當前線程,即t1線程  
  27.                 }  
  28.             }  
  29.             catch(InterruptedException th1){}  
  30.             finally{}  
  31.             System.out.println("t1 back!");  
  32.         }  
  33.         if(Thread.currentThread()==t2){  
  34.             System.out.println("t2");  
  35.             try{  
  36.                 synchronized(this){  
  37.                     wait();   
  38.                 }     
  39.             }  
  40.             catch(InterruptedException th2){}  
  41.             finally{}  
  42.             System.out.println("t2 back!");  
  43.         }  
  44.         if(Thread.currentThread()==t3){  
  45.             System.out.println("t3");  
  46.             try{  
  47.                 synchronized(this){  
  48.                     wait();   
  49.                 }     
  50.             }  
  51.             catch(InterruptedException th3){}  
  52.             finally{}  
  53.             System.out.println("t3 back!");  
  54.         }  
  55.         if(Thread.currentThread()==notify){  
  56.             System.out.println("notify");  
  57.             try{  
  58.                 synchronized(this){  
  59.                     this.notifyAll();     
  60.                 }     
  61.             }  
  62.             //catch(InterruptedException th3){}  
  63.             finally{}  
  64.         }  
  65.     }  
  66.  
  67.     public static void main(String args[]){  
  68.             Priority t=new Priority();  
  69.             t.t1.start();  
  70.             t.t2.start();  
  71.             t.t3.start();  
  72.               
  73.               
  74.             try{  
  75.                 {  
  76.                     Thread.sleep(2000);   
  77.                 }     
  78.             }  
  79.             catch(InterruptedException th3){}  
  80.             finally{}  
  81.             //t.notice();  
  82.             t.notify.start();  
  83.               
  84.             //System.exit(0);  
  85.     }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章