- package cn.itcast.demo03_生产和消费者问题;
- public class SetThread extends Thread{
- private BaoziPu bzp;
- public SetThread(BaoziPu b){
- this.bzp = b;
- }
- @Override
- public void run() {
- while(true){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- bzp.setBaozi("包子");
- }
- }
- }
- package cn.itcast.demo03_生产和消费者问题;
- public class GetThread extends Thread{
- private BaoziPu bzp;
- public GetThread(BaoziPu bzp){
- this.bzp = bzp;
- }
-
- @Override
- public void run() {
- while(true){
- String s = this.bzp.getBaozi();
- System.out.println(s);
- }
- }
- }
- package cn.itcast.demo03_生产和消费者问题;
- /*
- * 生产和消费者线程:
- *
- * 1.此例只适用于:"单生产者" 和 "单消费者" "模式";(至于多生产和多消费,可以上网搜索相关资料)
- * 2.让当前访问的线程等待:Object-->wait();
- * 唤醒当前所有等待的线程:Object --> notify()或notifyAll()
- * 3.wait()以及notify()和notifyAll()语句,必须放在"同步代码块"或"同步方法"内,否则抛出异常;
- */
- public class Demo {
- public static void main(String[] args) {
- BaoziPu bzp = new BaoziPu();
- SetThread setThread = new SetThread(bzp);
- GetThread getThread = new GetThread(bzp);
-
- setThread.start();
- getThread.start();
-
- }
- }
- package cn.itcast.demo03_生产和消费者问题;
- import java.util.ArrayList;
- import java.util.List;
- public class BaoziPu {
- private List<String> bzList = new ArrayList<>();
-
- public synchronized void setBaozi(String s){
- this.bzList.add(s);
- System.out.println("唤醒所有等待的消费者......");
- notifyAll();//notify()
-
- }
- public synchronized String getBaozi(){
- /*if(bzList.size() > 0){
- String s = bzList.get(0);
- bzList.remove(0);
- return s;
- }else{
- return null;
- }*/
- if(this.bzList.size() == 0){
- //让消费方等待
- try {
- System.out.println("没包子了,等会......");
- wait();
- System.out.println("来包子啦......");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- //取包子
- String s = bzList.get(0);
- bzList.remove(0);
- return s;
- }
- }
复制代码 |
|