zoukankan      html  css  js  c++  java
  • JAVA多线程通信

    JAVA多线程通信

    package com.frank.thread;
    /**   
     * author:pengyan    
     * date:Jun 16, 2011    
     * file:ProducerAndCustomerTest.java   
     */  
    public class ProducerAndCustomerTest {
    	public static void main(String[] args) {
    		//create an object 
    		Queue q=new Queue();
    		Productor p=new Productor(q);
    		Customer c=new Customer(q);
    		//p and c shared q
    		p.start();
    		c.start();
    	}
    }
    class Customer extends Thread{
    	Queue q;
    	public Customer(Queue q) {
    		this.q=q;
    	}
    	@Override
    	public void run() {
    		while (q.value<10) {//get the value
    			System.out.println("Customer get "+q.get());
    		}
    	}
    }
    class Productor extends Thread{
    	Queue q;
    	public Productor(Queue q) {
    		this.q=q;
    	}
    	@Override
    	public void run() {
    		for (int i = 1; i <=10; i++) {
    			q.put(i);//product and show info
    			System.out.println("Productor put "+i);
    		}
    	}
    }
    class Queue{
    	int value;//count the mumber
    	boolean bFull=false;//whether the cup is full
    	public synchronized void  put(int i){
    		if (!bFull) {
    			value=i;//fill the cup 
    			bFull=true;//it is full
    			notifyAll();//notify other thread
    			try {
    				wait();//wait.......
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	public synchronized int get(){
    		if (!bFull) {
    			try {
    				wait();//if not full,wait until full
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		bFull=false;//after got the cup is empty
    		notifyAll();//notify the Productor to put
    		return value;//return the value
    	}
    }
     

    控制台打印:

    Productor put 1

    Customer get 1

    Customer get 2

    Productor put 2

    Customer get 3

    Productor put 3

    Customer get 4

    Productor put 4

    Customer get 5

    Productor put 5

    Productor put 6

    Customer get 6

    Productor put 7

    Customer get 7

    Customer get 8

    Productor put 8

    Customer get 9

    Productor put 9

    Customer get 10

    Productor put 10


  • 相关阅读:
    linux下LD_PRELOAD的用处
    三个通用的脚本,处理MySQL WorkBench导出表的JSON数据进SQLITE3
    ubuntu 18.04下,KMS_6.9.1服务器启动后,客户端连接一段时间因为libnice而crash的问题修复
    Daliy Algorithm(线段树&组合数学) -- day 53
    Daliy Algorithm(链表&搜索&剪枝) -- day 52
    Daliy Algorithm(二分&前缀和) -- day 51
    每日算法
    动态规划--01背包模型
    每日算法
    每日算法
  • 原文地址:https://www.cnblogs.com/pengyan5945/p/5218370.html
Copyright © 2011-2022 走看看