015.2Condiction介面,

來源:互聯網
上載者:User

015.2Condiction介面,

Condiction對象能夠讓線程等待,也能夠喚醒相應的線程,通過下面方法,具體看代碼:
await();
signal();
signalAll();

使用步驟:
1)建立鎖
2)通過鎖拿到Condiction對象
3)Condiction對象等待後,就需要別人喚醒才會繼續執行該進程

例子代碼:

  1 import java.util.concurrent.locks.Condition;  2 import java.util.concurrent.locks.Lock;  3 import java.util.concurrent.locks.ReentrantLock;  4   5 public class NewProducerConsumerCondition  6 {  7   8     public static void main(String[] args)  9     { 10         Resource r = new Resource(); 11  12         //2,建立線程任務。 13         Producer pro = new Producer(r); 14         Consumer con = new Consumer(r); 15  16         //3,建立線程。 17         Thread t1 = new Thread(pro); 18         Thread t2 = new Thread(pro); 19         Thread t3 = new Thread(con); 20         Thread t4 = new Thread(con); 21  22         t1.start(); 23         t2.start(); 24         t3.start(); 25         t4.start(); 26     } 27  28 } 29  30 class Resource{ 31     private String name; 32     private int count = 1; 33     private final Lock lock = new ReentrantLock(); 34     private Condition produce = lock.newCondition(); 35     private Condition consume = lock.newCondition(); 36     private boolean flag = false; 37     public void set(String name) 38     { 39         lock.lock(); 40         try{ 41             while(flag){ 42                 try{produce.await();}catch(Exception e){}        //Condiction對象等待 43             } 44             this.name = name + count; 45             count += 1; 46             System.out.println(Thread.currentThread().getName()+"-----生產者-------"+this.name); 47             flag = true; 48             consume.signalAll(); 49         }finally{ 50             lock.unlock(); 51         } 52     } 53      54     public void out() 55     { 56         lock.lock(); 57         try{ 58             while(!flag){ 59                 try{consume.await();}catch(Exception e){} 60             } 61             System.out.println(Thread.currentThread().getName()+"-----消費者-------"+this.name); 62             flag = false; 63             produce.signalAll(); 64         }finally{ 65             lock.unlock(); 66         }  67     } 68 } 69  70 class Producer implements Runnable 71 { 72     private Resource r ; 73     // 生產者一初始化就要有資源,需要將資源傳遞到建構函式中。 74     Producer(Resource r) 75     { 76         this.r = r; 77     } 78     public void run() 79     { 80         while(true) 81         { 82             r.set("大白兔奶糖"); 83         } 84     } 85 } 86  87 class Consumer implements Runnable 88 { 89     private Resource r ; 90     // 消費者一初始化就要有資源,需要將資源傳遞到建構函式中。 91     Consumer(Resource r) 92     { 93         this.r = r; 94     } 95     public void run() 96     { 97         while(true) 98         { 99             r.out();100         }101     }102 103 }
View Code
class BoundedBuffer{    final Lock lock = new ReentrantLock();// 鎖    final Condition notFull = lock.newCondition(); // 生產    final Condition notEmpty = lock.newCondition(); // 消費    final Object[] items = new Object[100];// 儲存商品的容器。    int putptr/* 生產者使用的角標 */, takeptr/* 消費者使用的角標 */, count/* 計數器 */;    /* 生產者使用的方法,往數組中儲存商品 */    public void put(Object x) throws InterruptedException    {        lock.lock();        try {            while (count == items.length) // 判斷計數器是否已到數組長度。滿了。                notFull.await();// 生產就等待。            items[putptr] = x; // 按照角標將商品儲存到數組中            if (++putptr == items.length) // 如果儲存的角標到了數組的長度,就將角標歸零。                putptr = 0;            ++count;// 計數器自增。            notEmpty.signal();// 喚醒一個消費者        } finally {            lock.unlock();        }    }    public Object take() throws InterruptedException    {        lock.lock();        try {            while (count == 0) // 如果計數器為0,說明沒有商品,消費者等待。                notEmpty.await();            Object x = items[takeptr]; // 從數組中通過消費者角標擷取商品。            if (++takeptr == items.length) // 如果消費的角標等於了數組的長度,將角標歸零。                takeptr = 0;            --count;// 計數器自減。            notFull.signal();// 喚醒生產者。            return x;        } finally {            lock.unlock();        }    }}
能存多個商品的店

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.