国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

java - Beberapa keraguan tentang notify()/wait()
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-05-17 09:58:07
0
1
787
class MyObject{
    private Queue<String> queue = new ConcurrentLinkedQueue<String>();
    public synchronized void set(String s){
            while(queue.size() >= 10){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.add(s);
            notify();
    }
}

class Producer implements Runnable{
    private MyObject myObj;
    
    public Producer(MyObject myObj) {
        this.myObj= myObj;
    }

    @Override
    public void run() {
        // 每條線程執(zhí)行30次set
        for (int i = 0; i < 30; i++) {
            this.myObj.set("obj:" + i);
        }
    }
}

public static void main(String[] args){
    Producer producer = new Producer(new MyObject());
        
    // 生成30條線程
    for (int i = 0; i < 10; i++) {
        Thread thread = new Thread(producer);
        thread.start();
    }
    // 運(yùn)行結(jié)果是只set了30次
}

Ragu saya ialah apabila notify() menerbitkan pemberitahuan, mengapa ia tidak membiarkan kaedah wait() thread lain terus dilaksanakan?

PHP中文網(wǎng)
PHP中文網(wǎng)

認(rèn)證高級(jí)PHP講師

membalas semua(1)
習(xí)慣沉默

Apabila bilangan baris gilir anda melebihi 10, setiap utas anda akan bermula wait()住了, 不會(huì)走到notify()的啊. 你需要一個(gè)單獨(dú)的線程去監(jiān)控隊(duì)列的大小, 大于10的時(shí)候notify() dahulu, anda boleh menukar sedikit

class MyObject {
    private Queue<String> queue = new ConcurrentLinkedQueue<String>();

    private volatile int limit = 10;

    public synchronized void set(String s) {
      if (queue.size() >= limit) {
        try {
          wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      queue.add(s);
    }

    public synchronized void delta() {
      if (queue.size() >= limit) {
        limit += 10;
        notify();
      }
    }
}

Kemudian ada benang pemantauan

class Monitor implements Runnable {

    private MyObject myObj;

    public Monitor(MyObject myObj) {
      this.myObj = myObj;
    }

    @Override
    public void run() {
      while (true) {
        myObj.delta();
      }
    }
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan