本文内容来自互联网,如果侵权,请联系本人删除,会在获得信息后及时删除,谢谢!
实现生产者和消费者的消费同步,不会出现名字和性别混乱的结果:
直接上代码:
/**
* 多线程的生产者和消费者
*/
class Res {
// 姓名
public String name;
// 性别
public String sex;
}
// 生产线程
class InThread extends Thread {
public Res res;
public InThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (res) {
if (count == 0) {
res.name = "小红";
res.sex = "女";
} else {
res.name = "小明";
res.sex = "男";
}
count = (count + 1) % 2;
}
}
}
}
// 消费者
class OutThread extends Thread {
public Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
// 关键代码,使用锁确定为一个对象的内容
synchronized (res) {
System.out.println(res.name + ", " + res.sex);
}
}
}
}
public class ThreadPAndC {
public static void main(String[] args) {
Res res = new Res();
InThread inThread = new InThread(res);
OutThread outThread = new OutThread(res);
inThread.start();
outThread.start();
}
}
运行结果: