前两节已经给大家介绍很多有关线程的知识,今天主要给大家讲一下:线程间通讯。
什么是线程间通讯
其实就是多个线程操作同一共享资源,但它们的操作有所不同。
多线程操作需求
读写用户的操作;当写(Write)线程写完一条用户数据时,读线程(Reader)开始读取用户信息;达到写一条用户数据,通知读线程立刻开始读刚产生的用户数据。
共享资源对象:
/**
* @Created by
* @Date 2019/3/10 23:51
* @Description: 用户对象(也是多线程共享的资源)
*/
public class User {
/**
* 姓名
*/
public String name;
/**
* 性别
*/
public String sex;
public volatile static Boolean FLAG = false;
}
写线程:
/**
* @Created by
* @Date 2019/3/10 23:53
* @Description: 写线程
*/
public class WriterThread extends Thread {
private User user;
public WriterThread(User user) {
this.user = user;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (User.class) {
if (!user.FLAG) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count % 2 == 0) {
user.name = "小军";
user.sex = "男";
} else {
user.name = "小红";
user.sex = "女";
}
//count 在 0,1不断的切换
count = (count + 1) % 2;
//使当前线程等待
try {
User.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
user.FLAG = true;
} else {
User.class.notify();
}
}
}
}
}
读线程:
**
* @Created by
* @Date 2019/3/10 23:58
* @Description: 读线程
*/
public class ReadThread extends Thread {
/**
* 共享资源
*/
private User user;
public ReadThread(User user) {
this.user = user;
}
@Override
public void run() {
//不断的用户数据
while (true) {
synchronized (User.class) {
if (user.FLAG) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(user.name + " --> " + user.sex);
try {
User.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
user.FLAG = false;
}else {
User.class.notify();
}
}
}
}
}
测试代码:
/**
* @Created by
* @Date 2019/3/11 0:01
* @Description:
*/
public class Test001 {
public static void main(String[] args) {
//共享资源
User user =new User();
//写线程
WriterThread writerThread =new WriterThread(user);
//读线程
ReadThread readThread =new ReadThread(user);
//分别开启读写线程
writerThread.start();
readThread.start();
}
}