• 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


  • 相关阅读:
    Java 定时任务
    Swing中常用的方法
    瀑布流ajax分页
    权限管理
    图片自动加水印
    jsp自动生成静态页(提供思路)
    分页查询语句
    使用phpmailer发送邮件(以QQ邮箱为例)
    在浏览器的标签页显示网站标志图标(或指定图标)的方法
    随机生成验证码
  • 原文地址:https://www.cnblogs.com/pengyan5945/p/5218370.html
Copyright © 2020-2023  润新知