线程报错--多生产多消费的高效率模式(不是很明白这个和lock、condition有什么区别)
package itcast.messagethread71;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
Lock:
一个锁上多个监视器对象
*/
public class MessageThread71 {
public static void main(String[] args) {
Resource r = new Resource();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class MyLock
{
public static final Object LOCKA = new Object();
public static final Object LOCKB = new Object();
}
class Resource
{
private String name;
private int count = 1;
private boolean flag;//是否有商品的标记
public void set(String name)
{
synchronized(MyLock.LOCKA)
{
while(flag)
{
try {
wait();//t1(醒了),t2 t1醒了唤醒了t2
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name + "--" + count;
count++;
System.out.println(Thread.currentThread().getName() + "生产了 ," + this.name);
flag = true;
MyLock.LOCKB.notify();
}
}
public void get()//synchronized(this)写的有点冤,就直接同步函数就行了
{
synchronized(MyLock.LOCKB)
{
while(!flag)
{
try {
wait();//t3,t4
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "消费了......" + this.name);
flag = false;
MyLock.LOCKA.notify();
}
}
}
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r = r;
}
public void run() {
while(true)
{
r.set("蛋糕");
}
}
}
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r = r;
}
public void run() {
while(true)
{
r.get();
}
}
}