目錄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(); } } }