【基础编程题】多线程====写一个多线程的小程序

题目 :写一个多线程的小程序,要求如下:

1). 有多个线程,一个线程为生产者,其他线程为消费者;
2). 生产者生产商品,未消费的商品达到 20 件时就休息,小于 20 件时就继续生产;
3). 消费者消费商品,当没有可消费的商品时就休息,有可消费的商品时就继续消费;
4). 主入口函数 main 的输入参数有 3 个,分别为:消费者线程个数,生产速度(件/秒),消费速度(件/秒)。例如消费者线程个数为 2,生产速度为 8(即每 125 ms 生产 1 件商品),消费速度为 3(即每 1000/3 ms 消费 1 件商品)


代码如下:

public class Product {
	private static ArrayList<Integer> product = new ArrayList<Integer>();
	private static Object obj = new Object();

	public static void main(String[] args) {
		System.out.println("开始启动线程");
		startProduct( 2,8,3);
	}

	private static void startProduct(int consumerSize,int produceSpeed,int consumerSpeed){
		//启动生产者
		new Producer(produceSpeed).start();
		//启动消费者
		for(int i=1;i<=consumerSize;i++){
			new Consumer(i,consumerSpeed).start();
		}
		System.exit(0);
	}
	
	private static class Producer extends Thread{
		int n;//生产速度
		int i;//生产者所有生产的第几个商品
		Producer(int n){
			this.n=n;
		}

		@Override
		public void run() {

			while(true){
				try {
					Thread.sleep(1000/n);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				synchronized (obj) {
					if(product.size()==20){
						try {
							System.out.println("生产商品达到20,停止生产!!");
							obj.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}else{
						int num = 10000+i++;
						product.add(num);
						System.out.println("生产者生产了商品,商品编号"+num);
						obj.notifyAll();
					}
				}
			}
		}
	}

	private static class Consumer extends Thread{
		int n;//消费者数
		int speed;//消费速度
		Consumer(int n,int speed){
			this.n=n;
			this.speed =speed;
		}

		@Override
		public void run() {
			while(true){
				try {
					Thread.sleep(1000/speed);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (obj) {
					if(product.size()==0){
						try {
							System.out.println("商品已消费完!!");
							obj.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}else{
						Integer a = product.remove(0);
						System.out.println("消费者"+n+"消费了商品"+a);
						obj.notifyAll();
					}
				}
			}
		}
	}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值