天天看点

生产电脑|学习笔记

开发者学堂课程【Java 高级编程:生产电脑 】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:

https://developer.aliyun.com/learning/course/20/detail/300

生产电脑 

多线程案例分析二

题目:设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,则搬运工要等待新电脑产出,如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产,并统计出生产的电脑数量。

在本程序之中实现的就是一个标准的生产者与消费者的处理模型,实现操作的代码如下:

package cn.mldn.demo;

class Producer implements Runnable {

private Resource resource;

public Producer (Resource resource) {

this.resource = resource ;

public void run(){

class Resource{

private Computer computer ;

public synchronized void make() throws Exception{if (this.computer !=null){//已经生产过了

super.wait();

this.computer=newComputer("MLDN牌电脑,",1.1);

super.notifyAll();

public synchronized void get() throws Exception {

if (this.computer == null)  {//没有生产过

super.wait();

System.out.println(this. computer);

private Resource resource ;

public Consumer ( Resource resource)  {

this.resource = resource ;

public voidrun() {

for(int x = 0 ;x< 50;x++)  {

try  {

this.resource.get();

catch (Exception e)  {

e.printStackTrace( );

class Resource

private Computer computer ;

publicsynchronized void make() throws Exception {if (this. computer != null) {//已经生产过了

super.wait( );

Thread.sleep(100);

this.computer=newComputer("MLDN牌电脑",1.1) ;

System.out.print1n("生产" + this. computer);

super.notifyAll();

public synchronized void get() throws Exception {

if (this. computer == null) (//没有生产过

super .wait();

Thread.sleep(10);

System.out.println("生产电脑" + this. computer);this. computer = null ; //已经取走了super.notifyAll();