zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    [BZOJ2179]FFT快速傅立叶
    [UOJ#34]多项式乘法
    [BZOJ4636]蒟蒻的数列
    [BZOJ4632]树的编码
    [BZOJ1070][SCOI2007]修车
    [BZOJ1529][POI2005]ska Piggy banks
    [BZOJ2654]tree
    腾讯应用管理中心,腾讯开放平台应用认领
    Sony/索尼 NW-ZX300A ZX300 无损音乐播放器4.4口
    read progress
  • 原文地址:https://www.cnblogs.com/goldlong/p/10953871.html
Copyright © 2011-2022 走看看