资源共享:
//共享资源
public class Resource {
public static int num = 0;
public static final String LOCK = "lock";//共享的锁
}
消费者:
//消费者线程
public class ConsumerTask implements Runnable {
//必须保证:消费者线程和生产者线程使用同一个对象锁
@Override
public void run() {
while (true) {
//同步代码块
synchronized (Resource.LOCK) {
if (Resource.num == 0) {
//没有:等待
try {
System.out.println(Thread.currentThread().getName() + "没有产品,等待中~~~");
Resource.LOCK.wait();//无限等待(会释放对象锁)
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//有:消费
System.out.println(Thread.currentThread().getName() + " 有产品,开始消费"+Resource.num);
Resource.num--;
Resource.LOCK.notify();//唤醒:生产者
}
}
}
}
}
生产者:
public class ProducerTask implements Runnable {
//必须保证:消费者线程和生产者线程使用同一个对象锁
@Override
public void run() {
while(true) {
synchronized (Resource.LOCK) {
if (Resource.num == 0) {
//没有:生产
System.out.println(Thread.currentThread().getName() + " 没有产品,开始生产~~");
Resource.num = 1;
Resource.LOCK.notify(); //唤醒:消费者
} else {
try {
//有:等待
System.out.println(Thread.currentThread().getName() + " 资源不足无法生成,等待中....");
Resource.LOCK.wait();//释放掉锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
测试:
public class Test1 {
public static void main(String[] args) {
new Thread(new ConsumerTask() ,"消费者").start();
new Thread(new ProducerTask(),"生产者").start();
}
}