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:如果全部读完了,就等待

上一篇:java多线程快速入门(二十一)


下一篇:java多线程快速入门(十八)