首页 > 学院 > 开发设计 > 正文

线程_生产消费模型

2019-11-08 01:15:26
字体:
来源:转载
供稿:网友

资源类:

package com.www.thread1;public class StringBuffered { PRivate StringBuffer s = new StringBuffer(); //定义一个StringBuffer用来表示货架 public synchronized void append(){ String name = Thread.currentThread().getName(); //获取当前线程的名称 char a = (char) (65+ (int)(Math.random()*26)); //产生一个随机的字符 s.append(a); //将随机字符a添加到s上 System.out.println(a + "产生了" + name); this.notify(); //唤醒this上wait的线程 } public synchronized void delete() throws Exception{ String name = Thread.currentThread().getName(); //获取当前线程的名称 if(s.length()==0){ //如果s的长度为0,消费者线程wait this.wait(); }else{ char a = s.charAt(0); //取出商品线程添加的a s.deleteCharAt(0); //将s中的位置清空,等待下一轮生产 System.out.println(name+"取出了" + a); } }}

生产者线程

package com.www.thread1;public class ProT extends Thread{ //生产者线程 StringBuffered s; public ProT(StringBuffered s){ this.s = s; } public void run(){ while(true){ s.append(); } }}

消费者

package com.www.thread1;public class ComT implements Runnable { //消费者线程 StringBuffered s; public ComT(StringBuffered s) { this.s = s; // TODO Auto-generated constructor stub } public void run() { while(true){ try { //调用删除方法。 s.delete(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // TODO Auto-generated method stub }}

测试类:

package com.www.thread1;public class Test { public static void main(String[] args) { StringBuffered sb = new StringBuffered(); //创建StringBuffered的对象 ProT t = new ProT(sb); //创建生产者对象 Runnable rc = new ComT(sb); Thread tc = new Thread(rc,"rc"); //创建消费者对象 t.start(); tc.start(); //启动线程 }}

控制台输出:

R产生了Thread-0 Z产生了Thread-0 K产生了Thread-0 rc取出了Y rc取出了M rc取出了D rc取出了Q rc取出了H


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表