第二单元作业——电梯系列

第二单元作业——电梯系列

单元作业总结

  • 电梯系列是第一次接触线程、锁等概念,也是第一次进行多线程编程。
    顺利的完成了三次作业,实现了多线程,算是基本的进步。
    课下学习的主要资源记录如下:
    Java并发编程-入门篇很多Java并发编程的基础知识都是看其中博客学习的。

  • 但是本次作业问题比取得的进步多太多,三次作业也有两次大翻车,问题在于测试不够认真。这个在以后的作业要多加注意改进。

分析总结作业设计策略。

第一次作业

  • 傻瓜电梯。单线程多线程都能成功,运用了单例模式和消费者生产者模型。

  • 单例模式如下

public class Singleton {
	private static volatile Singleton singleton; private Singleton() {}
	public static Singleton getInstance() { 
		if (singleton == null) {
			synchronized (Singleton.class) { 
				if (singleton == null) {
					singleton = new Singleton(); 
				}
			} 
		}
		return singleton; 
	}
}
  • 以及消费者生产者模型
public class Producer extends Thread { 
	private Tray tray; 
	private int id; 
	public Producer(Tray t, int id) {
		tray = t; 
		this.id = id; 
	} 
	public void run() {
		int value;
		for (int i = 0; i < 10; i++)
			for(int j =0; j < 10; j++ ) {
				value = i*10+j;
				tray.put(value); 
				System.out.println("Producer #" + this.id + " put: ("+value+ ").");
      	try { 
      		sleep((int)(Math.random() * 100)); 
      	} catch (InterruptedException e) { }
			}; 
		}
	}
}

public class Consumer extends Thread { 
	private Tray tray;
	private int id;
	public Consumer(Tray t, int id) {
		tray = t; 
		this.id = id; 
	} 
	public void run() {
		int value = 0;
		for (int i = 0; i < 10; i++) {
			value = tray.get();
			System.out.println("Consumer #" + this.id + " got: " + value); 
		} 
	}
}

public class Tray {
	private int value; 
	private boolean full = false; 
	public synchronized int get() {
		while (full == false) {
			try { wait(); } catch (InterruptedException e) { } 
		}
		full = false; // 􏰐􏰜full􏰖true􏰗􏱬􏰖false􏰚􏰓􏰣􏰥􏰟􏰑􏰡􏰛􏱋􏱃􏰞􏰕􏱟􏰔􏰙
		notifyAll();
	  return value;
	}
	
	public synchronized void put(int v) { 
		while (full == true) {
			try { 
				wait();
			} catch (InterruptedException e) { } 
      full = true; 
      value = v; 
      notifyAll();
    }
  }
}

第二次作业

  • 加入ALS电梯,引入观察者模式
private void notifyObservers() { 
	Vector<Observer> obs=null; 
	synchronized(MONITOR) {
		if(mObservers !=null)
			obs = mObservers.clone();
	}
	if (obs != null) {
		for (Observer observer : obs) { 
			observer.onObservableChanged();
		}
	}
}
  • 捎带,是日常电梯中非常常见的一种调度,这里要求非常多的对象之间的交互,每个对象只做他应该要做的事情,对象和对象之间所做的事情应该平均

第三次作业

  • 多线程智能电梯
    • 引入开闭原则和工厂模式
    • 加入两个学习链接,开闭原则工厂模式
    • 多部电梯,对线程间交互提出了更高的要求,线程安全要求也越高了。

基于度量的分析

  • 三次作业中,第一次作业最容易,类图也最简单,各种度量标准也最简单。
  • 第二次作业最复杂,但是第三次又取得了进步。

第一次作业

h5类图

h5_type

h5_method

第二次作业

h6类图

h6_type

h6_method

第三次作业

h7类图

h7_type

h7_method

自己Bug分析

  1. 程序结束问题较大,第三次作业得到修复
  2. 存在过度复杂的难以维护的容易出错的类,第三次作业得到改进

别人Bug分析

  • 多采用黑盒测试
  • 没找到别人的bug。

心得体会

  • 本次作业学会了单例模式、开闭模式、工厂方法
  • 学会了多线程编程、锁机制。
  • 程序测试方法还需要多加学习
posted @ 2019-04-24 11:50  yzy11235  阅读(222)  评论(0编辑  收藏  举报