目录html
电梯系列是第一次接触线程、锁等概念,也是第一次进行多线程编程。
顺利的完成了三次做业,实现了多线程,算是基本的进步。
课下学习的主要资源记录以下:
Java并发编程-入门篇不少Java并发编程的基础知识都是看其中博客学习的。java
可是本次做业问题比取得的进步多太多,三次做业也有两次大翻车,问题在于测试不够认真。这个在之后的做业要多加注意改进。git
傻瓜电梯。单线程多线程都能成功,运用了单例模式和消费者生产者模型。github
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; // fulltruefalse notifyAll(); return value; } public synchronized void put(int v) { while (full == true) { try { wait(); } catch (InterruptedException e) { } full = true; value = v; notifyAll(); } } }
private void notifyObservers() { Vector<Observer> obs=null; synchronized(MONITOR) { if(mObservers !=null) obs = mObservers.clone(); } if (obs != null) { for (Observer observer : obs) { observer.onObservableChanged(); } } }