本篇文章给大家带来的内容是关于java中消费者问题的代码分析,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
public class Resource {
//当前资源的数量
int num = 0;
//当前资源的上限
int size = 10;
//消费资源
public synchronized void remove() {
//如果num为0,没有资源了,需要等待
while (num == 0) {
try {
System.out.println("消费者进入等待");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果线程可以执行到这里,说明资源里有资源可以消费
num--;
System.out.println("消费者线程为:" + Thread.currentThread().getName() + "--资源数量:" + num);
this.notifyAll();
}
//生产资源
public synchronized void put() {
//如果资源满了,就进入阻塞状态
while (num == size) {
try {
System.out.println("生产者进入等待");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
System.out.println("生产者线程为:" + Thread.currentThread().getName() + "--资源数量:" + num);
this.notifyAll();
}
}public class Consumer implements Runnable {
private Resource resource;
public Consumer(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
while (true){
resource.remove();
}
}
}public class Producer implements Runnable {
private Resource resource;
public Producer(Resource resource){
this.resource=resource;
}
@Override
public void run() {
while (true){
resource.put();
}
}
}public class TestConsumerAndProducer {
public static void main(String[] args) {
Resource resource = new Resource();
//生产线程
Producer p1 = new Producer(resource);
//消费线程
Consumer c1 = new Consumer(resource);
new Thread(p1).start();
new Thread(c1).start();
}
}
相关推荐:
以上就是Java中消费者问题的代码分析的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号