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();
    }
}
相關文章
相關標籤/搜索