java 大数据(多线程同步) 整理二

package com.xc.thread.prodcomsumer;

/**
 * 多线程 票池
 * @author Administrator
 *
 */
class DeadLockApp{
	public static void main(String[] args) {
		//使用java中集合类,list是列表
		Pool pool=new Pool();
		Productor p1=new Productor("生产者",pool);
		p1.setName("p1");
		Consumer c1= new Consumer("消费者",pool);
		c1.setName("c1");
		Consumer c2= new Consumer("消费者",pool);
		c2.setName("c2");
		p1.start();
		c1.start();
		c2.start();
	}
	//生产者-线程
	class Productor extends Thread{
		int  i = 0;
		private String name;
		private Pool pool;
		public Productor(String name,Pool poll) {
			this.name = name;
			this.pool = pool;
		}
		public void run() {
			while(true) {
				pool.add(i++);
			}
		}
	}
	
	//消费者-线程
	class Consumer extends Thread{
		private String name;
		private Pool pool;
		public Consumer(String string, Pool pool2) {
			// TODO Auto-generated constructor stub
		}
		public void run() {
			while(true) {
				pool.remove();
			}
		}
	}
	
	//票池
   class  Pool{
		private java.util.List<Integer> list =new java.util.ArrayList<Integer>();
		//容器最大值
		private int MAX = 1;
		//添加元素
		public void add(int n) {
			//同步
			synchronized (this) {
				try {
				//获得当前线程的名称
				String name =Thread.currentThread().getName();
				//循环判断
				while (list.size()==MAX) {
					//打印某个线程等待
					System.out.println(name+".wait()");
					//线程等待,时间片1秒,等待1秒开始抢线程
					this.wait(1000);
				}
				list.add(n);
				System.out.println(name+":"+n);
				System.out.println(name+".notify()");
				//通知
				this.notify();
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		//删除元素
		public int remove() {
			//同步块
			synchronized (this) {
				try {
				String name =Thread.currentThread().getName();
				//仓库为空
				while (list.size()==0) {
					System.out.println(name+".wait()");
					//线程等待,时间片1秒,等待1秒开始抢线程
					this.wait(1000);
				}
				//为空,减去一个元素
				int i= list.remove(0);
				System.out.println(name +"-:"+i);
				System.out.println(name+".notify()");
				//通知
				this.notify();
				return i;
				}
				catch(Exception e) {
					e.printStackTrace();
				}
				return -1;
			}
		}
	}
	
	
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值