• 4.多线程之间的通讯


    什么是多线程的通讯?
    多线程之间的通讯,其实就是多个线程同时去操作同一个资源,但是操作动作不同
     
     
    package com.jlong;
     
    class User {
        public String name;
        public String sex;
     
        public boolean flag=false;
    }
     
    class InputThread extends Thread {
        private User user;
     
        public InputThread(User user) {
            this.user = user;
        }
     
        int cout = 0;
     
        @Override
        public void run() {
     
            while (true) {
                synchronized (user) {
                    if(user.flag){
                        try {
                            user.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
     
                    if (cout == 0) {
                        user.name = "jLong";
                        user.sex = "男";
                    } else {
                        user.name = "燕子";
                        user.sex = "女";
                    }
                    cout = (cout + 1) % 2;
                    user.flag=true;
                    user.notify();
                }
     
            }
        }
    }
     
    class OutputThread extends Thread {
     
     
        private User user;
     
        public OutputThread(User user) {
            this.user = user;
        }
     
        @Override
        public void run() {
            while (true) {
                synchronized (user) {
                    if(!user.flag){
                        try {
                            user.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(user.name + "--" + user.sex);
                    user.flag=false;
                    user.notify();
                }
     
            }
        }
    }
     
    public class ThreadDemo01 {
        public static void main(String[] args) {
            User user = new User();
            InputThread inputThread = new InputThread(user);
            OutputThread outputThread = new OutputThread(user);
            inputThread.start();
            outputThread.start();
        }
    }
  • 相关阅读:
    automatic preferred max layout width
    UIActivityIndicatorView
    collectionview不能拖动
    消除找不到文件路径的警告
    保存图片到本地和相册
    svn上传.a文件
    UILabel copyWithZone:]: unrecognized selector sent to instance 0x7fd662d8f9b0
    NSString NSURL
    iOS 定位功能
    前端实现左右翻页功能Demo
  • 原文地址:https://www.cnblogs.com/goldlong/p/10953871.html
Copyright © 2020-2023  润新知