多线程数据同步:管程法———wait() notifyAll()

package thread;

import java.util.Random;

/**
 * 生产消费者模式,管程法
 * 
 * @author Administrator
 *
 */
public class TestStackThread {
	public static void main(String[] args) {
		TestStack testStack = new TestStack();
		new PushChar(testStack).start();
		;
		new PopChar(testStack).start();
	}
}

class PushChar extends Thread {
	private TestStack stack;

	public PushChar(TestStack stack) {
		this.stack = stack;
	}

	public void run() {
		Random random = new Random();
		for (int i = 0; i < 1000; i++) {
			stack.push((char) (random.nextInt(26) + 65));
		}
	}
}

class PopChar extends Thread {
	private TestStack stack;

	public PopChar(TestStack stack) {
		this.stack = stack;
	}

	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("出栈" + stack.pop());
		}
	}
}

class TestStack {
	private char[] character = new char[10];
	private int index = 0;

	public synchronized void push(char c) {
		// 栈满则等待数据出栈
		while (index == character.length) {
			try {
				System.out.println("栈满,等待数据出栈……");
				wait();// 线程阻塞,等待数据出栈后唤醒
			} catch (InterruptedException e) {
			}
		}
		System.out.println("入栈" + c);
		character[index] = c;
		index++;
		notifyAll();// 释放对象锁,通知正在等待的线程重新占有
	}

	public synchronized char pop() {
		while (index == 0) {
			try {
				System.out.println("栈空,等待数据入栈……");
				wait();
			} catch (InterruptedException e) {
			}
		}
		index--;
		char c = character[index];
		notifyAll();
		return c;
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值