多線程下要注意的地方:
1. this.wait()和this.notify()要成對使用;
2. 對於sychronized要謹慎. 上鎖/不上鎖要謹慎考慮. 用了可能會在效率上下降, 不用可能導致不可預測的結果值.
3. wait 和 thread.sleep()有很大差別: wait是object類中的方法, 而sleep是thread下的方法. wait表示指的是當前的線程進行wait...
而sleep是認為的控制等待等待多少時間後再執行.
4. 線程建立有兩種方法
1: class mythread implements Runnable{
public void run(){
..... .
}
}
mythread mt = new mythread ();
Thread t = new Thread(mt);
t.start();
2. 從Thread繼承
class mythread extends Thread {
public void run() {
..... .
}
}
}
mythread mt = new mythread ();
mt.start();
以蒸窩窩頭為例:消費者生產者代碼:
public class ProducerConsumer{public static void main( String args[] ){SynStack ss = new SynStack();Producer p = new Producer(ss);Consumer c = new Consumer(ss);Thread t = new Thread(p);Thread t2 = new Thread(c);t.start();t2.start();}}class WoTou{int id;WoTou( int _id ){ id = _id; }public String toString(){return id;}}class SynStack{WoTou[] arrWoTou = new WoTou[6];//蒸籠大小為6
private int idx = 0;public synchronized void push( WoTou wt ){//if( idx == arrWoTou.length) { //用if如果出現了 中斷錯誤, 那麼會跳出if體. 也會出錯, 所以用while
while( idx == arrWoTou.length ){try{System.out.println("to many wotou.. please wait ```");this.wait();//
}catch( InterruptedException e ){e.printStackTrace();}}arrWoTou[idx++] = wt;this.notify();//被所定的對象上 , 通知他們..當前這個進程上有哪個在等待對應的資訊,叫醒他們.
}public synchronized WoTou pop(){//if( idx == 0 ) {while( idx == arrWoTou.length ){try{System.out.println("no wotou.. please wait ```");this.wait();// 指的是當前的線程進行wait...
}catch( InterruptedException e ){e.printStackTrace();}}this.notify();return arrWoTou[--idx];}}class Producer implements Runnable{SynStack ss = null;Producer( SynStack _ss ){ss = _ss;}public void run(){for( int i = 0; i < 20; i++ ){WoTou wt = new WoTou(i);System.out.println("produce : " + wt);ss.push(wt);try{Thread.sleep(3000);} catch( InterruptedException e ){e.printStackTrace();}}}}class Consumer implements Runnable{SynStack ss = null;Consumer( SynStack _ss ){ss = _ss;}public void run(){for( int i = 0; i < 20; i++ ){WoTou wt = new WoTou(i);System.out.println("consume : " + wt);ss.pop();System.out.println(wt);try{Thread.sleep(1000);} catch( InterruptedException e ){e.printStackTrace();}}}}
可以改變下代碼中的 wait, notify等... 來看下其作用..