标签:
任何一个时刻,对象的控制权(monitor)只能被一个线程拥有。
无论是执行对象的wait、notify还是notifyAll方法,必须保证当前运行的线程取得了该对象的控制权(monitor)
如果在没有控制权的线程里执行对象的以上三种方法,就会报java.lang.IllegalMonitorStateException异常。
JVM基于多线程,默认情况下不能保证运行时线程的时序性
IllegalMonitorStateException wait 还是notify 都必须确保自己取得对象的锁
如果不使用wait¬ify的话,线程就会一直尝试去占用锁,会浪费性能。
wait 会释放锁 但是notify会释放吗? 如果不会释放 会发生什么事情 。
不会释放 如果释放了线程运行到一半会有问题 一直要到整个同步语句自行完成之后才会释放。
package org.famous.unyielding.current;
import java.util.Vector;
public class Client {
public static void main(String[] args) {
int goods = 0;
Object pLock = new Object();
Vector<String> message = new Vector<String>();
Thread customer = new Thread(new Customer(message, "customer", pLock));
Thread producter = new Thread(new Producter(message, "producter", pLock));
customer.start();
producter.start();
}
}
package org.famous.unyielding.current;
import java.util.Vector;
/**
*
* @author patzheng
*
*/
public class Customer implements Runnable {
private Vector<String> messages = new Vector();
private String threadName;
private Object pLock;
public Customer(Vector<String> messages, String threadName, Object pLock) {
this.messages = messages;
this.threadName = threadName;
this.pLock = pLock;
}
@Override
public void run() {
Thread.currentThread().setName(threadName);
System.err.println(Thread.currentThread().getName() + "Goods‘s size" + messages.size());
synchronized (pLock) {
while (true) {
if (messages.size() <= 0) {
try {
pLock.wait();
System.err.println("customer wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.err.println(Thread.currentThread().getName() + "Goods‘s size" + messages.size());
System.err.println("customer notify producer");
messages.remove(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pLock.notify();
}
}
}
}
}
package org.famous.unyielding.current;
import java.util.Date;
import java.util.Vector;
public class Producter implements Runnable {
private Vector<String> messages = new Vector();
private String threadName;
private Object pLock;
public Producter(Vector<String> messages, String threadName, Object pLock) {
this.messages = messages;
this.threadName = threadName;
this.pLock = pLock;
}
@Override
public void run() {
Thread.currentThread().setName(threadName);
System.err.println(Thread.currentThread().getName() + "Goods‘s size" + messages.size());
synchronized (pLock) {
while (true) {
if (messages.size() >= 1) {
try {
System.err.println("producer wait");
pLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
messages.add(new Date().toString());
System.err.println(Thread.currentThread().getName() + "Goods‘s size" + messages.size());
System.err.println("producer notify customer");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pLock.notify();
}
}
}
}
}
标签:
原文地址:http://my.oschina.net/payzheng/blog/513167