看了毕向东老师的生产者消费者,就照着视频参考运行了一下,感觉还好
这个值得学习的是条理特别清晰:
ProducterConsumerDemo.java中,一个资源类Resources,生产者消费者都可以访问的到。
生产者类Producter,消费者Consumer都实现了Runnable接口,在其中的run方法中实现重载,对共享资源进行生产和消费
优化:
如果以后需要加入项目中,对ProducterConsumerDemo类中加一个构造方法,public ProducterConsumerDemo(){...},实例化对象即可调用
代码:
class ProducterConsumerDemo
{
public static void main(String[] args)
{
Resources r =new Resources();
Productor pro =new Productor(r);
Consumer con = new Consumer(r); Thread t1 =new Thread(pro);
Thread t2 =new Thread(con);
t1.start();
t2.start();
System.out.println("Hello World!");
}
} class Resources
{
private String name;
private int count =1;
private boolean flag =false; public synchronized void set(String name)
{
if(flag)
try{this.wait();}catch(Exception e){}
this.name = name+"--"+count++; System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
flag =true;
//唤醒对方进程
this.notify(); }
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exception e){} System.out.println(Thread.currentThread().getName()+" ....消费者...."+this.name);
flag =false;
//唤醒对方进程
this.notify(); }
} class Productor implements Runnable
{
private Resources res;
Productor(Resources res){
this.res =res;
}
public void run(){
while(true){
res.set("++商品++");
}
} } class Consumer implements Runnable
{
private Resources res;
Consumer(Resources res){
this.res =res;
}
public void run(){
while(true){
res.out();
}
} }
由于自己需要的功能是,生产者消费者对一个二维数组进行操作,所以在其基础上加了资源Resources类的成员属性。实现存取功能
算是一个框架吧,留存:
class ProducterConsumerArr2D
{
public static void main(String[] args)
{
Resources r =new Resources();
Productor pro =new Productor(r);
Consumer con = new Consumer(r); Thread t1 =new Thread(pro);
Thread t2 =new Thread(con);
t1.start();
t2.start();
System.out.println("Hello World!");
}
} class Resources
{
private String name;
private int count =1;
private float[][] arr2D=new float[5][5]; //为它分配5行5列的空间大小
private boolean flag =false; public synchronized void set(String name)
{
if(flag)
try{this.wait();}catch(Exception e){}
//需放在count++前面
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{
arr2D[i][j]=(float)count;
}
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"生产者"+this.name); flag =true;
//唤醒对方进程
this.notify(); }
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exception e){} System.out.println(Thread.currentThread().getName()+" ....消费者...."+this.name+"二维数组任意元素"+arr2D[2][2]);
flag =false;
//唤醒对方进程
this.notify(); }
} class Productor implements Runnable
{
private Resources res;
Productor(Resources res){
this.res =res;
}
public void run(){
while(true){
res.set("++二维数组存取++");
}
} } class Consumer implements Runnable
{
private Resources res;
Consumer(Resources res){
this.res =res;
}
public void run(){
while(true){
res.out();
}
} }
ProducterConsumerArr2D.java
当然,这个只针对支持两个互相独立的线程,如果继续加入多个线程(>2)肯定还会有资源数据出错的问题,继续学习