如果有什么不好的地方,请大家多多指教...
- //注意,优先级并不能确保运行的次序,仅仅是看谁能占有更多的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);
- }
- }