Java 线程多线程编程3---线程同步之生产者与消费者问题

生产者与消费者问题:

第一步:把架子搭起来

package com.zhj.www;public class ProceduerConsumer {public static void main(String[] args) {}
}//馒头实体
class wotou{int id;wotou(int id) {this.id = id;}public String toString() {return "wotou : "+id;}}	
//馒头栈
class syncStack{int index = 0;wotou[] arrWT= new wotou[6];//这个容器只能装6个馒头syncStack(int index) {this.index = index;}//往里仍馒头,之所以使用synchronized关键字,是因为防止多个人同时往里扔,public synchronized void push(wotou wt) {arrWT[index] = wt;    /*这两行不能分开index++;               */}//从里面取馒头,拿最上面的那一个public synchronized wotou pop() {index--;return arrWT[index];}}
/*多个生产者,也就是多个线程同时在执行*/
//生产者,用于对馒头栈的引用,他需要知道生产完馒头,需要往哪个筐里仍馒头
class proceduer implements Runnable{syncStack  ss= null;proceduer(syncStack ss) {this.ss = ss;}/*run方法对应着生产过程*/public void run() {for(int i =0;i<20;i++) {wotou wt = new wotou(i);ss.push(wt);}}
}
//消费者
class consumer implements Runnable{syncStack  ss= null;consumer(syncStack ss) {this.ss = ss;}public void run() {for(int i =0;i<20;i++) {wotou wotou  =ss.pop();System.out.println(wotou);}}
}

第二步:

需要考虑当馒头筐满了怎么办?马上就会报错?在push方法里考虑,让这个线程休息一下;

wait方法来源于object;wait的时候这把锁也就不属于我了。但是sleep的时候我仍然抓住这把锁。

package com.zhj.www;import java.io.IOException;public class ProceduerConsumer {public static void main(String[] args) {syncStack ss = new syncStack();proceduer proceduer = new proceduer(ss);consumer consumer  = new consumer(ss);new Thread(proceduer).start();new Thread(consumer).start();}
}//馒头实体
class wotou{int id;wotou(int id) {this.id = id;}public String toString() {return "wotou : "+id;}}	
//馒头栈
class syncStack{int index = 0;wotou[] arrWT= new wotou[6];//这个容器只能装6个馒头//往里仍馒头,之所以使用synchronized关键字,是因为防止多个人同时往里扔,public synchronized void push(wotou wt)  {if(index == arrWT.length){try {this.wait();//当前对象正在执行push方法需要wait}catch (InterruptedException e) {e.printStackTrace();}}this.notify();//哪个线程在等待就唤醒哪个线程arrWT[index] = wt;    /*这两行不能分开*/index++;                }//从里面取馒头,拿最上面的那一个public synchronized wotou pop() {if(index == 0) {try {this.wait();}catch (InterruptedException e) {e.printStackTrace();}}this.notify();//object类里的方法,唤醒一个;index--;return arrWT[index];}}
/*多个生产者,也就是多个线程同时在执行*/
//生产者,用于对馒头栈的引用,他需要知道生产完馒头,需要往哪个筐里仍馒头
class proceduer implements Runnable{syncStack  ss= null;proceduer(syncStack ss) {this.ss = ss;}/*run方法对应着生产过程*/public void run() {for(int i =0;i<20;i++) {wotou wt = new wotou(i);ss.push(wt);System.out.println("生产了:"+wt);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
}
//消费者
class consumer implements Runnable{syncStack  ss= null;consumer(syncStack ss) {this.ss = ss;}public void run() {for(int i =0;i<20;i++) {wotou wotou  =ss.pop();System.out.println("消费了:"+wotou);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
}

运行过程:


可以发现生产一个馒头,就消耗一个馒头。

完善之后的栗子:

package com.zhj.www;import java.io.IOException;public class ProceduerConsumer {public static void main(String[] args) {syncStack ss = new syncStack();proceduer proceduer = new proceduer(ss);consumer consumer  = new consumer(ss);new Thread(proceduer).start();new Thread(consumer).start();}
}//馒头实体
class wotou{int id;wotou(int id) {this.id = id;}public String toString() {return "wotou : "+id;}}	
//馒头栈
class syncStack{int index = 0;wotou[] arrWT= new wotou[6];//这个容器只能装6个馒头//往里仍馒头,之所以使用synchronized关键字,是因为防止多个人同时往里扔,public synchronized void push(wotou wt)  {while(index == arrWT.length){try {this.wait();//当前对象正在执行push方法需要wait}catch (InterruptedException e) {e.printStackTrace();}}this.notify();//哪个线程在等待就唤醒哪个线程arrWT[index] = wt; /*这两行不能分开*/index++;                }//从里面取馒头,拿最上面的那一个public synchronized wotou pop() {while(index == 0) {try {this.wait();}catch (InterruptedException e) {e.printStackTrace();}}this.notify();//object类里的方法,唤醒一个;	index--;return arrWT[index];}}
/*多个生产者,也就是多个线程同时在执行*/
//生产者,用于对馒头栈的引用,他需要知道生产完馒头,需要往哪个筐里仍馒头
class proceduer implements Runnable{syncStack  ss= null;proceduer(syncStack ss) {this.ss = ss;}/*run方法对应着生产过程*/public void run() {for(int i =0;i<20;i++) {wotou wt = new wotou(i);ss.push(wt);System.out.println("生产了:"+wt);try {Thread.sleep((int)(Math.random()*200));} catch (InterruptedException e) {e.printStackTrace();}}}
}
//消费者
class consumer implements Runnable{syncStack  ss= null;consumer(syncStack ss) {this.ss = ss;}public void run() {for(int i =0;i<20;i++) {wotou wotou  =ss.pop();System.out.println("消费了:"+wotou);try {Thread.sleep((int)(Math.random()*1000));} catch (InterruptedException e) {e.printStackTrace();}}}
}

运行之后。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/274013.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

windows 服务实例

参考来源:http://blog.csdn.net/morewindows/article/details/6858216 参考来源: http://hi.baidu.com/tfantasy/item/aefa43d66b470a2b38f6f76c 剩下的都是我自己整理的。 在VS2012中新建一个Windows 服务的项目。然后在解决方案目录下找到Services1.cs&#xff0c;切换到代码…

Java 线程多线程编程2---线程同步

来模拟一个死锁&#xff08;互相等待&#xff09;&#xff1a; TestDeadLock.java package com.zhj.www;public class TestDeadLock implements Runnable {public int flag 1;static Object o1 new Object();static Object o2 new Object();public void run() {System.out.p…

Java网络编程1---基础

TCP/IP:事实上的标准 自己编的应用程序&#xff1a;应用层 TCP/UDP层 IP层 物理层 数据封装&#xff1a;第五层只与第四层打交道。 数据拆封《TCP/IP详解》网络底层 IP巨大的贡献&#xff1a;提供了独一无二的IP地址。 内网IP&#xff1a;虚假的 子网掩码&#xff1a;255.255.2…

Java网络编程2---Socket-TCP编程

Sockct:插座Socket是关于TCP的。 端口号&#xff1a;两个字节->65536个端口号&#xff0c;一个应用程序占多个端口号&#xff1b; 但是假设一个应用程序占一个端口号&#xff1b;一台电脑会有65535个应用程序。 自己编写程序要占用端口号1024以上后的。 80端口&#xff1a;网…

winform绑定多张图片

开发winform程序的时候经常设计到要显示多张图片的问题&#xff0c;其解决思路一般是先遍历文件夹中的所有图片&#xff0c;然后再把这些图片添加到ImageList控件中&#xff0c;最后再绑定显示出来。这里我们介绍两种绑定的方法&#xff1a; &#xff08;一&#xff09;动态生成…

Java网络编程3---Socket-UDP编程

栗子&#xff1a;TestUDPServer.java 服务器端&#xff1a; package com.zhj.www;import java.net.DatagramPacket; import java.net.DatagramSocket;public class TestUDPServer {public static void main(String[] args)throws Exception {byte buf[] new byte[1024];Datagr…

iOS 6 自动布局入门

http://www.raywenderlich.com/zh-hans/22873/ios-6-自动布局-入门&#xff0d;1转载于:https://www.cnblogs.com/ihojin/p/auto-layout.html

Java GUI 基础知识

这部分主要包含AWT、组件和容器、布局管理器Component&#xff1a;所有可以和用户交互的图形元素&#xff0c;他的子类有&#xff1a;输入框… Java.awt及其子包 Container&#xff1a;容器&#xff0c;容纳其他各种各样的Component的元素。 Panel&#xff1a;可以容纳其他元素…

UVA11300

初步解题原理:代数运算单元素极值 代数运算: xi表示第i个给i-1的数量&#xff0c;正负表示给或得 c(a1a2a3....an)/n a1-x1x2c -->x2x1-a1c a2-x2x3c -->x3x1-a1-a22c a3-x3x4c -->x4x1-a1-a2-a33c ...... an-xnx1c -->xnx1-a1-a2-a3....-a(n-1)(n-1)c ansmax{|x1|…

Java GUI 基础知识2 监听机制

TestActionEvent.java没有调用方法&#xff0c;但是有反应。反应自己要编写程序有反应。 事件模型&#xff1a;一定要有某些反应。 写程序&#xff0c;监听的操作是自动发生的&#xff0c;一直监听。钩子函数&#xff0c;&#xff08;回调函数&#xff09; 怎么让它自动执行&am…

求字符串的最长回文字串 O(n)

昨天参加了某公司的校园招聘的笔试题&#xff0c;做得惨不忍睹&#xff0c;其中就有这么一道算法设计题&#xff1a;求一个字符串的最长回文字串。我在ACM校队选拔赛上遇到过这道题&#xff0c;当时用的后缀数组AC的&#xff0c;但是模板忘了没写出代码来。 回头我把这道题目再…

数据结构 二、向量(接口与实现and可扩容向量)

ADT操作实例&#xff1a;Disordered&#xff1a;显示出3对逆序紧邻对。Vector模板类初始有效空间为0&#xff1b;基于复制的构造描述区间&#xff1a;左闭右开 为什么*2&#xff1f;有限时间内不必要为扩容而打断。 2、可扩充向量左移一位&#xff1a;加一倍

数据库:mysql 获取刚插入行id[转]

我们在写数据库程序的时候,经常会需要获取某个表中的最大序号数, 一般情况下获取刚插入的数据的id&#xff0c;使用select max(id) from table 是可以的。但在多线程情况下&#xff0c;就不行了。 下面介绍三种方法 (1) getGeneratedKeys()方法: 程序片断: Connection conn ; …

svn由于连接方在一段时间后没有正确答复或连接的主机没有反应连接尝试失败...

解决方法&#xff0c;关掉防火墙&#xff0c; service iptables status 查看iptables状态 service iptables restart iptables服务重启 service iptables stop iptables服务禁用 转载于:https://www.cnblogs.com/jiqing9006/p/3347441.html

Android 服务(Service)

一、服务的解释 服务&#xff08;Service&#xff09;是Android中实现后台运行的解决方案&#xff0c;它适合那些去执行不需要和用户交互而且还要求长期运行的任务。服务的运行不依赖任何的与任何用户界面&#xff0c;即使程序被切换到后台&#xff0c;或者用户打开了另外一个应…

CenOS 配置C/C++语言

1.下载eclipseCDT组合包。 2.电脑上安装GCC&#xff0c; G 3.在eclipse上创建一个C project 4. Eclipse CDT功能很强大&#xff0c;安装完虽然可以编译运行c程序&#xff0c;但有个问题&#xff0c;就是找不到c标准库的头文件&#xff0c;无法打开诸如之类的文件&#xff0c;编…

(数据结构)前缀,后缀以及中缀表达式

中缀表达式&#xff08;中缀记法&#xff09; 中缀表达式是一种通用的算术或逻辑公式表示方法&#xff0c;操作符以中缀形式处于操作数的中间。中缀表达式是人们常用的算术表示方法。 前缀表达式&#xff08;前缀记法、波兰式&#xff09; 前缀表达式是一种没有括号的算术表…

Moravec角点检测算子

Moravec角点检测算子 Moravec 在1981年提出Moravec角点检测算子[1]&#xff0c;并将它应用于立体匹配。 首先, 计算每个像素点的兴趣值, 即以该像素点为中心, 取一个w*w(如:5x5)的方形窗口, 计算0度、45度、90度、135度四个方向灰度差的平方和, 取其中的最小值作为该像素点的兴…

java习题-练习1

1、 Given the string, check if it is a palindrome.&#xff08;回文&#xff09; Example For inputString "aabaa", the output should becheckPalindrome(inputString) true;For inputString "abac", the output should becheckPalindrome(inputSt…

文件夹生成工具

很简单的一个小工具,输入一个字符串,可以为你生成相应的文件夹. 至于有什么用?我公司一个策划拿一顿饭给我要的. 下载地址: http://pan.baidu.com/s/1d0ewl 转载于:https://www.cnblogs.com/WhyEngine/p/3350053.html