一,wait() 和wait(long)
方法属性:wait(long) 为native方法,是Object类中,声明的;wait()方法时再Thread类中声明,其本质,调用的是Object的wait(long)方法,参数为0.
唤起方式:调用线程的notify和notifyall方法,或者timing out
使用方式:wait()方法,放在循环中使用,源码建议使用方式:
* synchronized (obj) {
* while (<condition does not hold>)
* obj.wait(timeout, nanos);
* ... // Perform action appropriate to condition
* }
举个例子,生产者消费者模式的实现:
生产者代码:
package com.blog.thread;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerThread2 extends Thread{
private Object monitor;
LinkedBlockingQueue<String> data = null;
public ProducerThread2(Object monitor,LinkedBlockingQueue<String> data) {
this.monitor = monitor;
this.data = data;
}
@Override
public void run() {
//线程起来了,就让他一直跑
int i = 0;
while(true) {
synchronized (monitor) {
//超过10个了就停止生产
while(data.size()>10) {
System.out.println("超过十个,等待消费");
try {
monitor.wait(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
data.put("张三"+i);
i++;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
消费者代码:
package com.blog.thread;
import java.util.concurrent.LinkedBlockingQueue;
public class ConsumerThread2 extends Thread{
private Object monitor;
LinkedBlockingQueue<String> data = null;
public ConsumerThread2(Object monitor,LinkedBlockingQueue<String> data) {
this.monitor = monitor;
this.data = data;
}
@Override
public void run() {
//一直跑
while(true) {
synchronized (monitor) {
if(data.size()==0) {
System.out.println("全部消费了,赶紧生产");
monitor.notify();
}
}
try {
Thread.currentThread().sleep(1000);
System.out.println(data.take());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
测试main方法:
public static void main(String[] args) {
Object monitor = new Object();
LinkedBlockingQueue<String> data = new LinkedBlockingQueue<String>();
ConsumerThread consumerThread = new ConsumerThread(monitor, data);
ProducerThread producerThread = new ProducerThread(monitor, data);
consumerThread.start();
producerThread.start();
}
执行结果:
全部消费了,赶紧生产
超过十个,等待消费
张三0
张三1
张三2
张三3
张三4
张三5
张三6
张三7
张三8
张三9
张三10
全部消费了,赶紧生产
超过十个,等待消费
张三11
张三12
张三13
张三14
张三15
张三16
......
解析:当进入消费者的同步代码块时,将持有monitor的锁,这时候,调用wait方法,等待其他线程唤起;所有在生产者中,生产数目达到一定程度了,则调用notify方法,唤起,使得消费者执行;
注意,这里均使用的是Object的方法。