• 郝斌_生产消费


    80 81生产消费

    线程同步

    class SynStack {
    	private char data[] = new char[6];
    	private int cnt = 0;// 表示数组有效元素的个数
    
    	public synchronized void push(char ch) {
    		while (data.length == cnt) {
    			try {
    				this.wait();
    			} catch (Exception e) {
    
    			}
    		}
    
    		this.notify();
    
    		data[cnt] = ch;
    		cnt++;
    		System.out.println("生产线程正在生产第" + cnt + "个产品,该产品是:" + ch);
    	}
    
    	public synchronized char pop() {
    		char ch;
    
    		while (0 == cnt) {
    			try {
    				this.wait();
    			} catch (Exception e) {
    
    			}
    		}
    
    		this.notify();
    		ch = data[cnt - 1];
    		System.out.println("消费线程正在消费第" + cnt + "个产品,该产品是:" + ch);
    
    		--cnt;
    		return ch;
    	}
    }
    
    class Producer implements Runnable {
    	private SynStack ss = null;
    
    	public Producer(SynStack ss) {
    		this.ss = ss;
    	}
    
    	public void run() {
    		char ch;
    
    		for (int i = 0; i < 26; i++) {
    			try {
    				Thread.sleep(100);
    			} catch (Exception e) {
    			}
    
    			ch = (char) ('a' + i);
    			ss.push(ch);
    		}
    	}
    }
    
    class Consumer implements Runnable {
    	private SynStack ss = null;
    
    	public Consumer(SynStack ss) {
    		this.ss = ss;
    	}
    
    	public void run() {
    		for (int i = 0; i < 26; i++) {
    			try {
    				Thread.sleep(100);
    			} catch (Exception e) {
    			}
    
    			ss.pop();
    		}
    	}
    }
    
    public class Test {
    	public static void main(String[] args) {
    		SynStack ss = new SynStack();
    		Producer p = new Producer(ss);
    		Consumer c = new Consumer(ss);
    
    		Thread t1 = new Thread(p);
    		Thread t2 = new Thread(c);
    
    		t1.start();
    		t2.start();
    	}
    }
    
  • 相关阅读:
    解决方案 git@github.com出现Permission denied (publickey)
    github设置添加SSH
    base64是啥原理
    PHP面试题:HTTP中POST、GET、PUT、DELETE方式的区别
    PHP中put和post区别
    常用的微信编辑器
    局域网内一台电脑的ip地址自己会变,怎样让它不变
    Trendalyzer is an information visualization software
    FineReport报表和水晶报表的比较
    x
  • 原文地址:https://www.cnblogs.com/denggelin/p/6363361.html
Copyright © 2020-2023  润新知