java中wait 信号量和notify信号量的使用 (一)

2014-11-24 10:43:46 · 作者: · 浏览: 2

直接上代码,运行后看效果


[java]
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);
}


}

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 stat