> Java > java지도 시간 > 본문

Java의 소비자 문제에 대한 코드 분석

不言
풀어 주다: 2018-09-11 14:05:41
원래의
1724명이 탐색했습니다.

이 기사의 내용은 Java의 소비자 문제에 대한 코드 분석입니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

1.리소스

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();
    }
}
로그인 후 복사

2.소비자

public class Consumer implements Runnable {

    private Resource resource;

    public Consumer(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        while (true){
            resource.remove();
        }

    }
}
로그인 후 복사

3.프로듀서

public class Producer implements Runnable {

    private Resource resource;

    public Producer(Resource resource){
        this.resource=resource;
    }

    @Override
    public void run() {
        while (true){
            resource.put();
        }
    }
}
로그인 후 복사

4.테스트# 🎜🎜 #
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의 소비자 문제에 대한 코드 분석

관련 권장 사항:

Java 생산자와 소비자의 자세한 예# 🎜🎜##🎜 🎜#java 다중 스레드 동시 협업 생산자-소비자 디자인 패턴

위 내용은 Java의 소비자 문제에 대한 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!