线程通信
来源:互联网 发布:锐捷交换机ip mac绑定 编辑:程序博客网 时间:2024/06/09 14:26
线程通信
wait():在其他线程调用此对象的notify()方法或者notifyAll()f方法前导致当前线程等待
notify():唤醒的单条线程
notifyAll():唤醒全部线程
package com.briup.day19;import javax.swing.table.TableColumn;/** * 生产者和消费者案例 * */public class ProducterConsumer { public static void main(String[] args) { Product product = new Product(); new Thread(new Producer(product)).start(); new Thread(new Consumer(product)).start(); }}/** * 生产者 * */class Producer implements Runnable { private Product product; private int x = 0; public Producer(Product product) { this.product = product; } @Override public void run() { while (true) { synchronized (product) { //生 if(product.isHave) { //有产品的,则生产者进入等待状态 try { //等着,释放锁 product.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (x % 2 == 0) { // null null product.name = "包子"; product.type = "肉"; } else if (x % 2 == 1) { product.name = "饺子"; product.type = "素"; } // 有产品了 product.isHave=true; //唤醒消费者 product.notify(); x++; } } }}/** * 消费者 * * @author lixiaojian * */class Consumer implements Runnable { private Product product; public Consumer(Product product) { this.product = product; } @Override public void run() { while (true) { synchronized (product) { if (!product.isHave) { // 没产品了,消费者去等待 try { // 消 product.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(product.name + " " + product.type); // 包子 肉 // 没产品了 product.isHave = false; // 唤醒生产者 product.notify(); } } }}/** * 产品 * */class Product { String name; String type; boolean isHave = false;// 一开始是没产品的}
wait()和sleep()的区别是:sleep()方法不交出锁,相当于停止一定的时间而wait()这个方法是等待,锁交出其他的线程接到锁就可以运行
其实大家看了上面的案例不难发现,线程同步还是缜密的逻辑+同步线程
阅读全文
0 0
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- hi3559av100 编译 Hi3559AV100ES_SDK_V2.0.2.0 软件包 遇到的问题
- Go 指针练手
- Uncaught SyntaxError: Unexpected identifier
- 奥威Power-BI电力行业BI解决方案-电流分析
- 自定义控件——加减器
- 线程通信
- C++ : Object Model
- 区块链是什么?分布式账本技术入门指南
- MVP基本了解及使用和封装
- Sql语句中IN和exists的区别及应用
- sublime text3的安装插件
- sql中自连接的使用
- Error: Some file crunching failed
- xCode 9.0提交应用到iTunes Connet 报ERROR ITMS-90717: "Invalid App Store Icon. 解决办法