zoukankan      html  css  js  c++  java
  • 线程之间的通讯

    package com;

    /*
    * 生产类
    */
    public class Producer implements Runnable {
    //开始操作数据存储类P
    P q = null;

    public Producer(P q){
    this.q = q;
    }

    @Override
    public void run() {
    int i = 0;

    while(true){
    //编写往数据存储空间放入数据的代码
    if( i == 0 ){
    q.set("张三", "男");
    }else{
    q.set("李四", "女");
    }

    i = (i+1)%2;
    }
    }

    }

    package com;

    /*
    * 消费类
    */
    public class Consumer implements Runnable {
    //开始操作数据存储类P
    P q = null;

    public Consumer(P q){
    this.q = q;
    }

    @Override
    public void run() {
    while(true){
    //编写往数据存储空间取出数据的代码
    while( true ){
    q.get();
    }
    }
    }

    }

    package com;

    /*
    * 数据存储类
    */
    public class P {
    //数据存储空间
    private String name;
    private String sex;
    boolean bFull = false;//防止没有放入就不断读取或者没有取不断放入

    //加入set和get方法进行数据同步以免资源共享产生差异
    /*
    * wait(),notify(),notifyAll()方法只能在synchronized中调用
    */

    public synchronized void set(String name, String sex){
    if( bFull ){//正在放入,先等等
    try{
    wait();//后来的线程要等待
    }catch(InterruptedException e){

    }
    }

    this.name = name;

    try{
    Thread.sleep(10);
    }catch(Exception e){
    System.out.println(e.getMessage());
    }

    this.sex = sex;
    bFull = true;
    notify();//唤醒最先到达的线程
    }

    public synchronized void get(){
    if( !bFull ){//没有取,先等等
    try{
    wait();//后来的线程要等待
    }catch(InterruptedException e){

    }
    }

    System.out.println(this.name + "---->" + this.sex);
    bFull = false;
    notify();//唤醒最先到达的线程
    }
    }

    主类

    package com;

    public class ThreadCommunication {

    /**
    * 线程通讯
    */
    public static void main(String[] args) {
    P q = new P();
    new Thread(new Producer(q)).start();
    new Thread(new Consumer(q)).start();
    }

    }

  • 相关阅读:
    google protobuf
    spawn-fcgi和libfcgi源码解读
    [Linux] 查看进程的上下文切换pidstat
    [MySQL] update语句的redo log过程
    [转载] PHP 8新特性之JIT简介
    [PHP] 新浪企邮webmail在memcache实践使用共享session
    [Go] Golang练习项目-web客服系统即时通讯websocket项目go-fly
    [PHP] php8的jit不支持32位系统WARNING: JIT not supported by host architecture
    [PHP] 源码编译安装opcache
    [PHP] 查找使用的哪个配置文件php.ini
  • 原文地址:https://www.cnblogs.com/xingmeng/p/2445545.html
Copyright © 2011-2022 走看看