您的位置:首页 > 其它

Thread--不同步的生产者与消费者

2011-07-08 19:18 169 查看
/**

*

* 共享缓冲区的接口

*

*/

public interface Buffer {

//生产者使用的

public abstract void set(int value);

//消费者使用的

public abstract int get();

}

/**

*

* 消费者

*

*/

public class Consumer extends Thread{

/*缓冲区*/

private Buffer sharedLocation;

public Consumer( Buffer shared) {

super("Consumer");

sharedLocation = shared;

}

public void run() {

//用于存放从缓冲区中取出的数

int sum = 0;

for(int count = 1; count <= 4; count++) {

try {

Thread.sleep((int)(Math.random()*3001));

sum = sum + sharedLocation.get();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.println(getName() + "read values totaling:" + sum +

"./nTerminating" + getName() + ".");

}

}

/**

*

* 测试入口

*

*/

public class MainTestShareBuffer {

public static void main(String[] args) {

/*创建缓冲区*/

UnsynchronizedBuffer sharedLocation = new UnsynchronizedBuffer();

/*创建生产者与消费者 出生状态*/

Producer producer = new Producer(sharedLocation);

Consumer consumer = new Consumer(sharedLocation);

/*进入就绪状态*/

producer.start();

consumer.start();

}

}

/**

*

* 生产者

*

*/

public class Producer extends Thread {

//缓冲区

private Buffer sharedLocation;

public Producer(Buffer shared) {

super("Producer");

sharedLocation = shared;

}

public void run() {

for(int count = 1; count <= 4; count++){

try {

//如果没有调用sleep方法,并且如果生产者首先执行,则生产者极有可能在消费者

//获得执行机会之前完成它的任务。如果消费者首先执行,则该线程极有可能 在生产 者

//获得执行机机会之前完成它的任务。

Thread.sleep((int)(Math.random()*3001));

//生产

sharedLocation.set(count);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//err打印错误流

System.err.println(getName() + "done producing." +

"/nTerminating" + getName() + "."); //Termainat终止

};

}

/**

*

* 具体的缓冲区

*

* 含生产者和消费者线程共享的整数,两线程由set和get方法访问整数

*

*/

public class UnsynchronizedBuffer implements Buffer{

/*共享的数据*/

private int buffer = -1;

/**

* 消费者消费一个

*/

public int get() {

// TODO Auto-generated method stub

System.err.println(Thread.currentThread().getName() + " reads " + buffer);

return buffer;

}

/**

* 生产者生产一个

*/

public void set(int value) {

// TODO Auto-generated method stub

buffer = value;

System.err.println(Thread.currentThread().getName() + " writes " + value);

}

}
本文出自 “baiyan425” 博客,请务必保留此出处http://baiyan425.blog.51cto.com/1573961/606709
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: