为什么多线程总是离不开这个问题呢?
因为这种场景是多线程在生成环境中最重要,最主要的应用,基于这种场景提炼出的问题就是生产者消费者问题。
实例代码:
/**
* 资源
* @author PC
*
*/
class Resource {
int count = 0;
boolean isHas = false;
public synchronized void product() throws InterruptedException{
while(isHas){
wait(); //为了方便阅读 ,异常直接抛出了。
}
System.out.println(Thread.currentThread().getName() + "..生成了商品【"+(++count)+"】----");
isHas = true;
notifyAll();
}
public synchronized void consume() throws InterruptedException{
while(!isHas){
wait();
}
System.out.println(Thread.currentThread().getName() + "..消费了商品【"+count+"】");
isHas = false;
notifyAll();
}
}
/**
* 生产者
* @author PC
*
*/
class Producer implements Runnable{
Resource resource;
public Producer(Resource resource){
this.resource = resource;
}
public void run() {
while (true) {
try {
resource.product();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 消费者
* @author PC
*
*/
class Consumer implements Runnable{
Resource resource;
public Consumer(Resource resource){
this.resource = resource;
}
public void run() {
while (true) {
try {
resource.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource resource = new Resource();
new Thread(new Producer(resource)).start();
new Thread(new Producer(resource)).start();
new Thread(new Consumer(resource)).start();
new Thread(new Consumer(resource)).start();
}
}