直接上代码,运行后看效果
package Thread;
public class WaitAndNotifyTest {
public synchronized void wantTowait(int i ){
try {
System.out.println( i + " ready to wait ");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( i +" wait finsh");
}
public synchronized void wantToNotify(){
System.out.println( "ready to Notify ");
this.notify();
System.out.println( "Notify finsh");
}
public synchronized void wantToNotifyAll(){
System.out.println( "ready to NotifyAll ");
this.notifyAll();
System.out.println( "NotifyAll finsh");
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
final WaitAndNotifyTest w = new WaitAndNotifyTest();
Thread t1;
for(int i = 0 ; i < 10 ; i ++){
t1 = new Thread( new WaitAndNotifyProcessor( w , i ) );
t1.start();
}
Thread.sleep(2000);
w.wantToNotify();
Thread.sleep(2000);
w.wantToNotify();
Thread.sleep(2000);
w.wantToNotify();
Thread.sleep(2000);
w.wantToNotify();
Thread.sleep(2000);
w.wantToNotify();
Thread.sleep(2000);
w.wantToNotifyAll();
// Thread t2 = new Thread(
// new Runnable(){
//
// @Override
// public void run() {
// w.wantToNotify();
//
// }
//
//
// });
//
// t2.start();
}
}
package Thread;
public class WaitAndNotifyProcessor implements Runnable {
private WaitAndNotifyTest w ;
private int name;
public WaitAndNotifyProcessor( WaitAndNotifyTest w , int name){
this.w = w;
this.name = name;
}
@Override
public void run() {
if( name == 0){
try {
System.out.println("0 sleep 5000ms");
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
w.wantTowait( name);
}
}