JAVA全系列 教程
3762个小节阅读:7093.8k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
创建缓冲区
xxxxxxxxxx
/**
* 定义馒头类
*/
class ManTou{
private int id;
public ManTou(int id){
this.id = id;
}
public int getId(){
return this.id;
}
}
/**
* 定义缓冲区类
*/
class SyncStack{
//定义存放馒头的盒子
private ManTou[] mt = new ManTou[10];
//定义操作盒子的索引
private int index;
/**
* 放馒头
*/
public synchronized void push(ManTou manTou){
//判断盒子是否已满
while(this.index == this.mt.length){
try {
/**
* 语法:wait(),该方法必须要在synchronized块中调用。
* wait执行后,线程会将持有的对象锁释放,并进入阻塞状态,
* 其他需要该对象锁的线程就可以继续运行了。
*/
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//唤醒取馒头的线程
/**
* 语法:该方法必须要在synchronized块中调用。
* 该方法会唤醒处于等待状态队列中的一个线程。
*/
this.notify();
this.mt[this.index] = manTou;
this.index++;
}
/**
* 取馒头
*/
public synchronized ManTou pop(){
while(this.index == 0){
try {
/**
* 语法:wait(),该方法必须要在synchronized块中调用。
* wait执行后,线程会将持有的对象锁释放,并进入阻塞状态,
* 其他需要该对象锁的线程就可以继续运行了。
*/
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
this.index--;
return this.mt[this.index];
}
}
public class TestProduceThread {
public static void main(String[] args) {
}
}