zoukankan      html  css  js  c++  java
  • java多线程快速入门(十七)

    多线程通讯实例(必须要有多个线程、必须要管理同一个变量;线程A生产一个变量,线程B消费一个变量)

    package com.cppdy;
    
    class User {
    
        public String username;
        public String sex;
        //如果flag为false    证明变量可写不可读
        //如果flag为true    证明变量可读不可写
        public boolean flag=false;
    
    }
    
    class InputThread extends Thread {
        private User user;
    
        public InputThread(User user) {
            this.user = user;
        }
    
        @Override
        public void run() {
            int count = 0;
            while (true) {
                synchronized (user) {
                    
                    if(user.flag) {
                        try {
                            //这里是等待要去释放锁,线程会一直在这里等待,直到这个变量同一个user调用notify
                            user.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    
                    if (count % 2 == 0) {
                        user.username = "cppdy";
                        user.sex = "nan";
                    } else {
                        user.username = "吹泡泡的魚";
                        user.sex = "男";
                    }
                    count++;
                    //将user标记变为可读
                    user.flag=true;
                    //释放user锁
                    user.notify();
                }
            }
        }
    }
    
    class OutThread extends Thread {
        private User user;
    
        public OutThread(User user) {
            this.user = user;
        }
    
        @Override
        public void run() {
            while (true) {
                synchronized (user) {
                    if(!user.flag) {
                        try {
                            user.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(user.username + "--" + user.sex);
                    //将user标记变为可读
                    user.flag=false;
                    //释放user锁
                    user.notify();
                }
            }
        }
    }
    
    public class ThreadDemo13 {
    
        public static void main(String[] args) throws Exception {
            User user = new User();
            InputThread it = new InputThread(user);
            OutThread ot = new OutThread(user);
            it.start();
            ot.start();
        }
    
    }

    生产者线程A:如果有值还没读,就等待

    消费者线程B:如果全部读完了,就等待

  • 相关阅读:
    hdu 2647 Reward
    hdu 2094 产生冠军
    hdu 3342 Legal or Not
    hdu 1285 确定比赛名次
    hdu 3006 The Number of set
    hdu 1429 胜利大逃亡(续)
    UVA 146 ID Codes
    UVA 131 The Psychic Poker Player
    洛谷 P2491消防 解题报告
    洛谷 P2587 [ZJOI2008]泡泡堂 解题报告
  • 原文地址:https://www.cnblogs.com/jiefu/p/10016866.html
Copyright © 2011-2022 走看看