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 list =new java.util.ArrayList();
		//容器最大值
		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;
			}
		}
	}
	
	
}

 

你可能感兴趣的:(java大数据)