目的是回顧多線程的幾個(gè)api
多生產(chǎn)者+多消費(fèi)者+共享池文章來源地址http://www.zghlxwxcb.cn/news/detail-729879.html
public class Producer extends Thread{ private Store s; private String name; public Producer(Store s,String name) { this.s = s; this.name = name; } @Override public void run() { while (true){ synchronized (s){ if(s.isFull()){ try { s.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else{ try { s.add(name); Thread.sleep(300); s.notifyAll(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
public class Customer extends Thread{ private Store s; private String name; public Customer(Store s,String name) { this.s = s; this.name = name; } @Override public void run() { while (true){ synchronized (s){ if(s.isEmpty()){ try { s.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else { try { s.get(name); Thread.sleep(300); s.notifyAll(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
public class Store { private int size; private static final int MAX_SIZE = 20; public void get(String name) { size--; System.out.println("消費(fèi)者 "+name+"取出商品,池子里剩余獎(jiǎng)品數(shù)量: "+size); } public void add(String name) { size++; System.out.println("生產(chǎn)者 "+name+"放入商品,池子里剩余獎(jiǎng)品數(shù)量: "+size); } public boolean isEmpty(){ return size == 0; } public boolean isFull(){ return size == MAX_SIZE; } public int getSize(){ return size; } }
文章來源:http://www.zghlxwxcb.cn/news/detail-729879.html
到了這里,關(guān)于多線程之生產(chǎn)者消費(fèi)者的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!