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;
}
}
}
}