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

avatar 2017年05月29日10:45:37 0 2146 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此
题目
借助线程同步机制对四个线程进行输出

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

运行结果



本文链接:
  • 微信
  • 交流学习,服务定制
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0