public class Test {

    public static void main(String[] args) throws InterruptedException {
List<String> queue = new ArrayList<>();
new Thread(new PThread(queue)).start();
new Thread(new CThread(queue)).start();
}
} /**
* 生产者
*/
class PThread implements Runnable {
private List<String> queue;
private AtomicInteger i = new AtomicInteger(); public PThread(List<String> queue) {
this.queue = queue;
} @Override
public void run() {
while (true) {
synchronized(queue){
//如果queue有元素,那么就释放锁吧
if (queue.size() == 1) {
try {
queue.wait();// 释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
} else { //没有元素就生产一个元素
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String data = i.getAndIncrement() + "";
queue.add(data);
System.out.println("生产者线程,生产一个元素:"+data);
queue.notify(); //唤醒本线程,就可以获取锁了
}
}
}
}
} /**
* 消费者
*/
class CThread implements Runnable {
private List<String> queue; public CThread(List<String> queue) {
this.queue = queue;
} @Override
public void run() {
while (true) {
synchronized (queue) {
//如果queue中没有元素,就释放锁,让生产者去生产
if (queue.size() == 0) {
try {
queue.wait(); //就释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
} else { //消费元素
String data = queue.remove(0);
System.out.println("消费者线程,消费一个元素:"+data);
queue.notify();
}
}
}
}

最新文章

  1. Xcode常用技巧(1)-使用Xcode进行代码分析及GDB调试
  2. 怎样在 Ubuntu 中修改默认程序
  3. 在Linux下安装C/C++开发工具包的最佳方式
  4. MyBatis的学习总结三:优化MyBatis配置文件中的配置
  5. Labview中引用,属性节点,局部变量之间的区别
  6. [置顶] Asp.Net底层原理(二、写自己的Asp.Net框架)
  7. 使用python之环境管理
  8. 每日一练ACM 2019.0422
  9. Codeforces Round #517 (Div. 2)
  10. Actor模型和CSP模型的区别
  11. BOM嵌套简单写法
  12. 《spring boot 实战》读书笔记
  13. WDA基础一:激活相关服务
  14. WPF 中动态改变控件模板
  15. MVC的使用
  16. ReportViewer 安装
  17. HelloWorld 之JasperReports初步
  18. -【线性基】【BZOJ 2460】【BZOJ 2115】【HDU 3949】
  19. ubuntu中mysql版本升级到5.7
  20. linux文件系统命令和分区 挂载

热门文章

  1. threading.get_ident()
  2. 全文搜索 ElasticSearch
  3. 关于Nuget包安装之后再卸载,找不到dll的问题
  4. mysql优化工具(索引优化)
  5. &quot;CoolShell puzzle game&quot; writeup
  6. nmon内存分析
  7. Netty之大名鼎鼎的EventLoop
  8. vs code配置C/C++开发环境
  9. Java-多线程第一篇多线程相关认识(1)
  10. c#批量插入