class Do8
{
public static void main(String[] args)
{
Resource r =new Resource(); Input in =new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
} class Resource
{
String name;
String sex;
boolean flag=false;
}
//输入
class Input implements Runnable
{
Resource r;
Input(Resource r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(r)
{
if(r.flag)
{
try{r.wait();}catch(Exception e){}//为真的时候,当前线层停止
}
if(x==0)
{
r.name="往里";
r.sex="男";
}
else
{
r.name="xiaoli";
r.sex="wumen";
}
r.flag=true;
r.notify();//启动任意的停止的线层 } x=(x+1)%2; }
}
}
//输出
class Output implements Runnable
{
Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
{
try{r.wait();}catch(Exception e){}//不为真的时候,当前线层停止
}
try{Thread.sleep(100);}catch(Exception e){}
System.out.println(r.name+"..."+r.sex);
r.flag=false;
r.notify();//启动任意的停止的线层 }
}
}
}

练习

class Do9
{
public static void main(String[] args)
{
Resource r=new Resource();
Shengchan sc=new Shengchan(r);
Xiaoshou xs=new Xiaoshou(r);
Thread th1=new Thread(sc);
Thread th2=new Thread(xs);
th1.start();
th2.start();
}
} class Resource
{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name)
{
if(flag)
try{this.wait();}catch(InterruptedException e){}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
flag=true;
notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"..消费者........"+this.name);
flag=false;
notify();
}
}
class Shengchan implements Runnable
{
private Resource r; Shengchan(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
try{Thread.sleep(150);}catch(InterruptedException e){}
r.set("烤鸭");
}
} }
class Xiaoshou implements Runnable
{
private Resource r;
Xiaoshou(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
try{Thread.sleep(150);}catch(InterruptedException e){}
r.out();
}
}
}

最新文章

  1. [转]c++类的构造函数详解
  2. NeHe OpenGL教程 第一课:OpenGL窗口
  3. javascript倒计时代码
  4. 曾经的10道JAVA面试题
  5. Mono for Android 优势与劣势
  6. nyoj 756 重建二叉树
  7. JAVA的Executor框架
  8. 随机采样和随机模拟:吉布斯采样Gibbs Sampling
  9. MapReduce-序列化(Writable)
  10. 搭建openstack环境时出现的问题
  11. RbbitMQ 的 python 实现方法
  12. CentOS添加明细路由
  13. php+smarty轻松开发微社区/微论坛
  14. Python 创建和使用类
  15. Java中夏令时带来的Date不一致问题 (转)
  16. [转]使用Runtime.getRuntime().exec()方法的几个陷阱
  17. 【Floyd矩阵乘法】BZOJ1706- [usaco2007 Nov]relays 奶牛接力跑
  18. 0, \0, NULL
  19. ChemDraw绘制DNA结构的技巧
  20. 移动端:判断是否微信端、判断手机操作系统(ios或android)

热门文章

  1. MySQL和MsSQL实时自动同步---SyncNavigator 数据库同步软件
  2. idhttp post 上传或下载时显示进度条
  3. ASP.NET MVC下的异步Action的定义和执行原理
  4. 自定义cell 自适应高度
  5. 关于nginx架构探究(3)
  6. 转:CFile::Seek
  7. Altium Designer多图纸原理图设计方法探讨
  8. Qt之模型/视图(自定义按钮)(重绘QStyleOptionButton)
  9. 包含无数好东西的ownCloud
  10. TCP粘包的拆包处理