主界面
public class Master {
public static void main(String[] args) {
ArrayList<String> queue = new ArrayList<>();
}
模拟生产者线程
public class ThreadProduce extends Thread {
public ArrayList<String> queue;
public ThreadProduce(ArrayList<String> queue) {
this.queue = queue;
}
public void run() {
int id = 0;
while(true){
if(this.queue.size() == 0) {
id++;
String msg = "模拟数据"+id;
this.queue.add(msg);
System.out.println("生产者生产了数据"+msg);
}
try{
Thread.sleep(10);
}catch(Exception e){}
}
}
}
模拟消费者线程
public class ThreadCustomer extends Thread {
public ArrayList<String> queue;
public ThreadCustomer(ArrayList<String> queue) {
this.queue = queue;
}
public void run() {
while(true){
if(this.queue.size() > 0) {
String msg = this.queue.remove(0);
System.out.println("消费线程取出数据"+msg);
}
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
在主界面中启动线程
public class Master {
public static void main(String[] args) {
ArrayList<String> queue = new ArrayList<>();
ThreadProduce tp = new ThreadProduce(queue);
tp.start();
System.out.println("生产线程已启动");
ThreadCustomer tc = new ThreadCustomer(queue);
tc.start();
System.out.println("消费线程已启动");
}
}
运行效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/7701052915f1493fb1c71dcfe752a059.png)