设为首页 加入收藏

TOP

2012年计算机二级Java多线程之间的通讯学习教程
2014-11-03 09:45:08 】 浏览:3466
Tags:2012年 计算机 二级 Java 线程 之间 通讯 学习教程

7.3 多线程之间的通讯


  7.3.1 生产者和消费者


  多线程的一个重要特点是它们之间可以互相通讯。你可以设计线程使用公用对象,每个线程都可以独立操作公用对象。典型的线程间通讯建立在生产者和消费者模型上:一个线程产生输出;另一个线程使用输入。


  buffer让我们创建一个简单的"Alphabet Soup"生产者和相应的消费者.


  7.3.2 生 产 者


  生产者将从thread类里派生:


  class Producer extends Thread {


  private Soup soup;


  private String alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";


  public Producer(Soup s) {


  //Keep our own copy of the shared object


  this.soup = s;


  }


  public void run() {


  char c; //Throw 10 letters into the soup


  for (int i=0;i<10;i++) {


  c = alphabet.charAt((int)(Math.random() *26));


  soup.add(c); //print a record of osr addition


  System.out.println("Added"+c + "to the soup.");


  //wait a bit before we add the next letter


  try {


  sleep((int)(Math.random() *1000));


  }


  catch (InterruptedException e) {


   //


  }


  }


  }


  }


  注意我们创建了Soup类的一个实例。生产者用soup.add()函数来建立字符池。


  7.3.3 消费者


  让我们看看消费者的程序:


  public class Consumer extends Thread {


  private Soup soup;


  public Consumer (Soup s) {


  //keep our own copy of the shared object


  this.soup = s;


  }


  public void run() {


  char c;


  //Eat 10 letters from the alphabet soup


  for (int I=0 ;i<10;i++) {


  //grab one letter


  this.c = soup.eat();


  //Print out the letter that we retrieved


  System.out.println("Ate a letter: " +c); //


  try {


  sleep((int)(Math.raddom()*2000));


  }


  catch (InterruptedException e) {


  }


  ` }


  }


  }


  同理,象生产者一样,我们用soup.eat()来处理信息。那么,Soup类到底干什么呢?


  相关推荐:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇2012年计算机二级Java线程API列表.. 下一篇2012年计算机二级Java选择组件学..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目