zoukankan      html  css  js  c++  java
  • java线程间的通讯

    主要通过wait()和notify()方法进行线程间的通讯

    class Product extends Thread{
    	
    	String name;
    	float price;
    	boolean flag = false;
    			
    }
    
    class Productor extends Thread{
    	
    	Product p;
    	
    	public Productor(Product p) {
    		
    		this.p = p;
    		
    	}
    	int i = 0;
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		super.run();
    			while(true){
    				synchronized(p){
    					//通知生产者生产
    					//p.notify();
    				if(!p.flag){
    					if(i%2 == 0){
    						p.name = "苹果";
    						try {
    							Thread.sleep(10);
    						} catch (InterruptedException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    						p.price = 4.5f;
    						System.out.println("生产者生产了"+p.name+" 价格是"+p.price);
    					}
    					else{
    							p.name ="香蕉";
    							p.price = 2.5f;
    							System.out.println("生产者生产了"+p.name+"  价格是"+p.price);
    						}
    					i++;
    					p.flag = true;
    					p.notify();
    					
    				  }else{
    					  //生产了产品后等待消费者消费
    						try {
    							p.wait();
    						} catch (InterruptedException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    				     	}
    				}
    			}
    		}
    	}
    		
    }
    
    class Consumer extends Thread{
    
    	Product p;
    	public Consumer(Product p) {
    		
    		this.p = p;
    		
    	}
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		super.run();
    			while(true){
    				synchronized(p){
    					//通知启动消费者消费
    					//p.notify();
    					if(p.flag){
    							System.out.println("消费者消费了"+p.name+"价格是"+p.price);
    							p.flag = false;
    							p.notify();
    						}else{
    						//消费了产品后等待生产者生产
    						try {
    							p.wait();
    						} catch (InterruptedException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    					}
    					}
    				}
    		}
    	}
    

      

    //main方法
    	public static void main(String[] args) {
    
    		Product p = new Product();
    		
    		Productor productor = new Productor(p);
    		Consumer consumer = new Consumer(p);
    		productor.start();
    		consumer.start();
    		
    	}
    

      

  • 相关阅读:
    MVC,MVP和MVVM的区别
    将数组里某个属性相同的对象合并成一个数组
    Ajax的理解
    VUE如何关闭Eslint的方法
    数组去重
    vue-router传递参数的几种方式
    密码的显示和隐藏
    "校园易借查询"选题报告
    我的第一个微信好友分析
    数据库实践
  • 原文地址:https://www.cnblogs.com/it-life-nathan/p/6899783.html
Copyright © 2011-2022 走看看