博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 生产者消费者
阅读量:2344 次
发布时间:2019-05-10

本文共 1756 字,大约阅读时间需要 5 分钟。

public class NewThreadTest {
public static void main(String[] args){ Q1 q1 = new Q1(); new Thread(new Producter1(q1)).start(); new Thread(new Consumer1(q1)).start(); }}class Q1{
private String name = "Merry"; private String sex = "girl"; boolean bFull = false ; //synchronized线程锁保证线程原子操作安全 //和lock与unlock效果相同 public synchronized void put(String name,String sex){ if (bFull==true){ try { //告诉当前线程放弃监视器并进入休眠状态,等待其他线程进入该监视器notify()唤醒 wait(); }catch (Exception e){ e.printStackTrace(); } } this.name = name ; try{ Thread.sleep(1000); }catch (Exception e){ e.printStackTrace(); }finally { this.sex = sex; bFull = true ; notify(); } } public synchronized void get(){ if (bFull==false){ try { wait(); }catch (Exception e){ e.printStackTrace(); } } System.out.println(this.name+"-->>"+this.sex); bFull = false; //唤醒监视器的第一个线程 //notifyAll()唤醒监视器所有wait线程,优先级高的先被唤醒 notify(); }}class Producter1 implements Runnable{
Q1 q1 = null; public Producter1(Q1 q1){ this.q1 = q1 ; } @Override public void run() { int i=0; while (true){ if (i==0){ q1.put("BOB","boy"); }else {q1.put("Merry","girl"); } i = (i+1)%2; } }}class Consumer1 implements Runnable{
private Q1 q1 = null ; public Consumer1(Q1 q1){ this.q1=q1 ; } @Override public void run() { while (true){ q1.get(); } }}

转载地址:http://kqnvb.baihongyu.com/

你可能感兴趣的文章
angribird level editor
查看>>
love2d 苹果运行
查看>>
GridBagLayout 的注意
查看>>
ajax 跨域iis6 设置
查看>>
4.0版本改动
查看>>
IE8 9 ajax no-transport ajax 问题
查看>>
oracle 启动dbconsole
查看>>
entity-framework 6解决方案中多个项目使用
查看>>
ios基础
查看>>
unity3d
查看>>
metronic 1.5
查看>>
unity3d 4 assert store
查看>>
tab bar control 注意事项
查看>>
sql优化部分总结
查看>>
IDEA运行时动态加载页面
查看>>
UML总结(对九种图的认识和如何使用Rational Rose 画图)
查看>>
js遍历输出map
查看>>
easeui分页
查看>>
20个非常有用的Java程序片段
查看>>
Enterprise Architect使用教程
查看>>