• 那是从何处传来的钟声呢?偶尔听到那钟声,平添一份喜悦与向往之情。

Java线程生产者消费者简单应用

后端 Nanait 12年前 (2012-08-06) 845次浏览 已收录 0个评论 扫描二维码

题目

借助线程同步机制对四个线程进行输出

1 线程输出:甲、乙、丙、丁、戊

2 线程输出:aa、bb、cc、dd、ee

3 线程数出:A、B、C、D、E

4 线程输出:1、2、3、4、5

最终输出效果应该为:甲 aa A 1 乙 bb B 2 丙 cc C 3 丁 dd D 4 戊 ee E 5

分析

很显然,需要用到线程“生产者消费者”案例,即 wait()和 notify()的使用。

这里可以参考

Java 线程生产者和消费者实例

代码如下

  1. /*
  2.  *
  3.  * @author Nanait
  4.  *
  5.  */
  6. class Rescouce {
  7.     boolean flag = true;
  8. }
  9. class Thread1 extends Thread{
  10.     Rescouce res;
  11.     public Thread1(Rescouce res) {
  12.         this.res = res;
  13.     }
  14.     String []c1 = {“甲”,“乙”,“丙”,“丁”,“戊”};
  15.     String []c2 = {“aa”,“bb”,“cc”,“dd”,“ee”};
  16.     public  void run() {
  17.         synchronized (res) {
  18.             for(int i=0;i<5;i++) {
  19.                 while(!res.flag){
  20.                     try {
  21.                         res.wait();
  22.                     } catch (InterruptedException e) {
  23.                         e.printStackTrace();
  24.                     }
  25.                 }
  26.                 System.out.print(c1[i]+” “);
  27.                 System.out.print(c2[i]+” “);
  28.                 res.flag=false;
  29.                 res.notifyAll();
  30.             }
  31.         }
  32.     }
  33. }
  34. class Thread2 extends Thread{
  35.     Rescouce res;
  36.     public Thread2(Rescouce res) {
  37.         this.res = res;
  38.     }
  39.     String []c1 = {“A”,“B”,“C”,“D”,“E”};
  40.     String []c2 = {“1”,“2”,“3”,“4”,“5”};
  41.     public synchronized void run() {
  42.         synchronized (res) {
  43.             for(int i=0;i<5;i++) {
  44.                 while(res.flag){
  45.                     try {
  46.                         res.wait();
  47.                     } catch (InterruptedException e) {
  48.                         e.printStackTrace();
  49.                     }
  50.                 }
  51.                 System.out.print(c1[i]+” “);
  52.                 System.out.print(c2[i]+” “);
  53.                 res.flag=true;
  54.                 res.notifyAll();
  55.             }
  56.         }
  57.     }
  58. }
  59. public class Test {
  60.     public static void main(String[] args) {
  61.         Rescouce res = new Rescouce();
  62.         new Thread1(res).start();
  63.         new Thread2(res).start();
  64.     }
  65. }

运行结果

Java 线程生产者消费者简单应用


何处钟 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java 线程生产者消费者简单应用
喜欢 (0)
[15211539367@163.com]
分享 (0)

您必须 登录 才能发表评论!