java 多線程同步/ 消費者生產者問題.

來源:互聯網
上載者:User
多線程下要注意的地方:
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等... 來看下其作用..

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.