如果有什麼不好的地方,請大家多多指教...
- //注意,優先級並不能確保運行的次序,僅僅是看誰能佔有更多的CPU時間片
- class Priority implements Runnable{
- Thread t1,t2,t3,notify;
- Priority(){
- t1=new Thread(this);
- t1.setPriority(5);
- t2=new Thread(this);
- t2.setPriority(1);
- t3=new Thread(this);
- t3.setPriority(10);
- notify=new Thread(this);
- }
- public void notice(){
- synchronized(this){
- notify();
- }
- }
- public synchronized void run(){
- if(Thread.currentThread()==t1){
- System.out.println("t1");
- try{
- synchronized(this){
- wait(); //交出鎖並阻塞當前線程,即t1線程
- }
- }
- catch(InterruptedException th1){}
- finally{}
- System.out.println("t1 back!");
- }
- if(Thread.currentThread()==t2){
- System.out.println("t2");
- try{
- synchronized(this){
- wait();
- }
- }
- catch(InterruptedException th2){}
- finally{}
- System.out.println("t2 back!");
- }
- if(Thread.currentThread()==t3){
- System.out.println("t3");
- try{
- synchronized(this){
- wait();
- }
- }
- catch(InterruptedException th3){}
- finally{}
- System.out.println("t3 back!");
- }
- if(Thread.currentThread()==notify){
- System.out.println("notify");
- try{
- synchronized(this){
- this.notifyAll();
- }
- }
- //catch(InterruptedException th3){}
- finally{}
- }
- }
- public static void main(String args[]){
- Priority t=new Priority();
- t.t1.start();
- t.t2.start();
- t.t3.start();
- try{
- {
- Thread.sleep(2000);
- }
- }
- catch(InterruptedException th3){}
- finally{}
- //t.notice();
- t.notify.start();
- //System.exit(0);
- }
- }