线程间通信--生产消费
来源:互联网 发布:php输出当前时间 编辑:程序博客网 时间:2024/05/06 16:25
package thread;
public class Demo1 {
/**
* @线程间通信
* 其实就是多个线程在操作同一个资源,但是操作的动作不同
* 交替输出,可直接运行
*
*/
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex){
while(flag)
try {this.wait();} catch (InterruptedException e) {}
this.name = name;
this.sex = sex;
flag = true;
this.notifyAll();
}
public synchronized void out(){
while(!flag)
try {this.wait();} catch (InterruptedException e) {}
System.out.println(name+".........."+sex);
flag = false;
this.notifyAll();
}
}
class Input implements Runnable{
Res r = new Res();
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x==0)
r.set("lily", "female");
else
r.set("李明明", "男男男男男男男");
x = (x+1)%2;
}
}
}
class Output implements Runnable{
Res r = new Res();
Output(Res r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
public class Demo1 {
/**
* @线程间通信
* 其实就是多个线程在操作同一个资源,但是操作的动作不同
* 交替输出,可直接运行
*
*/
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex){
while(flag)
try {this.wait();} catch (InterruptedException e) {}
this.name = name;
this.sex = sex;
flag = true;
this.notifyAll();
}
public synchronized void out(){
while(!flag)
try {this.wait();} catch (InterruptedException e) {}
System.out.println(name+".........."+sex);
flag = false;
this.notifyAll();
}
}
class Input implements Runnable{
Res r = new Res();
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x==0)
r.set("lily", "female");
else
r.set("李明明", "男男男男男男男");
x = (x+1)%2;
}
}
}
class Output implements Runnable{
Res r = new Res();
Output(Res r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
0 0
- 线程间通信--生产消费
- 线程间通信:生产线程和消费线程
- java学习9:生产和消费问题,先生产才能消费,线程间通信与等待
- 多线程__【线程间通信】【等待唤醒机制】【多生产多消费】【Lock&Condition接口】
- 多线程__【线程间通信】【等待唤醒机制】【多生产多消费】【Lock&Condition接口】
- 线程生产消费模式
- 线程---生产消费问题
- 多线程通信【生产消费案例】
- 线程 --生产和消费问题
- java线程同步----生产消费
- 生产消费线程讲解例子
- 单线程生产,多线程消费
- 线程_生产消费模型
- Java 多线程间通信 多生产 多消费问题
- 多线程经典问题:馒头问题 生产和消费问题(线程的通信问题)
- 线程间的通信-生产消费者模式
- java生产消费线程小例子
- java线程之生产与消费
- Linux常用命令-文件处理命令
- 网址信息收集器
- Android设计模式系列-组合模式
- hdu4355
- nyoj 6 喷水装置(一)【贪心】
- 线程间通信--生产消费
- 编程之美:第四章 数字之趣 4.9数独知多少
- iTV android与客户端加密交互流程
- 第一篇博文
- B - 皇马
- 杭电2094产生冠军
- erlang数据类型atom
- java多线程之 ---- 线程死锁
- 用g++编译生成动态连接库*.so的方法及连接