题目内容
⽣产和消费问题描述
1. 使用集合类型java.util.Vector创建⼀个队列queue,可以向其中存⼊字符串数据。
2. 创建⼀个线程a,向该队列每隔1秒钟存⼊1个字符串,字符串内容自定义。
3. 创建另⼀个线程b,每隔1秒钟从该队列中取出并打印1个字符串。当队列queue中没有字符串时, 线程b打印“no msg”。
代码实现
Myqueue类
import java.util.Vector;
public class MyQueue {
private Vector<String>q = new Vector<>();
private int idx = 0;//当前队列头的下标
//获取队头元素
//使用synchronized可以保证不出异常
public synchronized void GetTop(){
if(q.size() <= idx) System.out.println("no msg");
else System.out.println("取出数据" + q.get(idx++));
}
//存入
public synchronized void Push(String k){
q.add(k);
System.out.println("存入数据" + k);
}
}
AAA类
public class AAA implements Runnable{
public MyQueue q;
//简单设置一些字符串
String[] arr = {"a","b","c","d","e","f","g"};
public AAA(MyQueue q) {
this.q = q;
}
@Override
public void run() {
for(int i = 0;i < arr.length;i++){
try {
Thread.sleep(1000);//休眠1s
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
q.Push(arr[i]);//添加
}
}
}
BBB类
public class BBB implements Runnable{
public MyQueue q;
public BBB(MyQueue q) {
this.q = q;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
q.GetTop();//读取队头
}
}
}
Main
public class Main {
public static void main(String[] args) {
MyQueue q = new MyQueue();//创建队列
AAA a = new AAA(q);
BBB b = new BBB(q);
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
//启动线程
t1.start();
t2.start();
}
}
实现效果
相关思考问题
对于第一个问题解决起来还是比较简单的,只需要将Myqueue类进行修改即可
具体来说就是引入一个标识flag来判断当前是否有元素
更改后的Myqueue类
import java.util.Vector;
public class MyQueue {
private Vector<String>q = new Vector<>();
private int idx = 0;//当前队列头的下标
private boolean flag = false;//表示是否有元素存入
//获取队头元素
//使用synchronized可以保证不出异常
public synchronized void GetTop(){
//无元素存入
if(flag == false){
try {
wait();//等待存入
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if(q.size() <= idx) System.out.println("no msg");
else System.out.println("取出数据" + q.get(idx++));
flag = false;//更改状态
notifyAll();//唤醒其他线程
}
//存入
public synchronized void Push(String k){
//有元素存入
if(flag == true){
try {
wait();//等待提取
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
q.add(k);
System.out.println("存入数据" + k);
flag = true;//更改状态
notifyAll();//唤醒其他线程
}
}
对于第二个问题解决起来与第一个问题类似,也只需要将Myqueue类进行修改即可
具体来说就是引入一个标识Flag方法 来判断当前存入元素个数是否超过2个即可
更改后的Myqueue类
import java.util.Vector;
public class MyQueue {
private Vector<String> q = new Vector<>();
private int idx = 0;//当前队列头的下标
//判断当前是否有两个元素
public boolean Flag(){
if(q.size() - idx >= 2)return true;
return false;
}
//获取队头元素
//使用synchronized可以保证不出异常
public synchronized void GetTop(){
if(Flag() == false){
try {
wait();//等待存入
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if(q.size() <= idx) System.out.println("no msg");
else System.out.println("取出数据" + q.get(idx++));
}
//存入
public synchronized void Push(String k){
q.add(k);
System.out.println("存入数据" + k);
notifyAll();//唤醒其他线程
}
}