1 调用wait()方法可以让线程等待,并释放对象锁,直到interrupt()方法中断它或者另一个线程调用notify()或者notify()All唤醒
2.wait()方法可以带个参数,此时不需要唤醒
3.调用notify()方法可以随机选择一个在该对象调用wait()方法的线程
4.notif和notifyAll()只能在同步方法或者同步块中使用
5.wait()和sleep()的区别是:wait()方法调用时会释放对象锁,而sleep()不会
以下为生产者消费者的例子:
public class ProRes {
/**
* @param args
*/
public static void main(String[] args) {
Product product=new Product();
Producer producer=new Producer(product);
Consumer consumer=new Consumer(product); }
}
class Product{
int n;
boolean valueset=false;//true表示有值可取,false便是需要放入新值
//消费方法
synchronized void get(){
//如果没有值,等待新值放入
if(!valueset){
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println(Thread.currentThread().getName()+"-Get:"+n);
//将valuset设置为false表示已取值
valueset=false;
//通知等待线程,放入新值
notify();
}
//消费方法
synchronized void put(int n){
//如果没有值,等待线程取值
if (valueset) {
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
}
this.n=n;
//将valueset设置为true,表示值已放入
valueset=true;
System.out.println(Thread.currentThread().getName()+"-put:"+n);
notify();
}
}
class Producer implements Runnable{
Product product;
Producer(Product product){
this.product=product;
new Thread(this,"Producer").start();
}
public void run() {
int k=0;
for (int i = 0; i < 5; i++) {
product.put(k++);
}
}
}
class Consumer implements Runnable{
Product product;
Consumer(Product product){
this.product=product;
new Thread(this,"Consumer").start();
}
public void run() {
//消费五次
for (int i = 0; i < 5; i++) {
product.get();
}
}
}