package thread.demo1;
/**单线程消费--生产
* @author: sys
* @Date: 2021/10/23/11:01 下午
* @Description:
*/
public class MyThread {
private Integer getIndex = 0;
private Integer putIndex = 0;
private Integer[] data = new Integer[10];
//生产者增加/消费者减少
private Integer size = 0;
public synchronized void put(Integer element) {
//已满进行阻塞
if (size == data.length) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 生产者放入
data[putIndex] = element;
++putIndex;
//设为0从头开始继续放
if (putIndex == data.length) {
putIndex = 0;
}
++size;
notify();
}
public synchronized Integer get() {
//没有了
if (size == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费者消费
Integer result = data[getIndex];
++getIndex;
//设置为0从头继续取
if (getIndex == data.length) {
getIndex = 0;
}
--size;
notify();
return result;
}
}
wait--notify/线程中的生成消费
最新推荐文章于 2024-08-16 23:08:28 发布