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();
    }
}
posted @ 2019-05-31 10:29  Gold_Long  阅读(145)  评论(0编辑  收藏  举报