您的位置:首页 > 编程语言 > Java开发

基于java多线程来实现生产者和消费者的实例

2013-03-21 21:51 671 查看
  声明:本实例是在网上看到,做了很小的修改。所以感谢之前的作者。只是一时忘了哪儿看到,没法加入链接,向原作者道歉,以示尊重。抱歉-^)...

同步栈:

class SycnStack {
private Integer index = 0;
private char[] data;

public SycnStack(int num) {
data = new char[num];
}

public void push(char c) {
synchronized (this) {// 对index加锁为何不行???必须this
while (index == data.length ) {
System.out.println(index +"  池子已满,不能放入!"
+ Thread.currentThread().toString());
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();// 获取锁
data[index] = c;
System.out.println(index +" 放入" + c + " "
+ Thread.currentThread().toString());
index++;
}
}

public Character pop() {
synchronized (this) {
while (index == 0) {
System.out.println(index +" 池子已空,取不了了!"
+ Thread.currentThread().toString());
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
char c = data[index];
System.out.println(index +" 取出" + c + " "
+ Thread.currentThread().toString());
return c;
}
}
}


生产者和消费者:

class Producer implements Runnable {
private SycnStack stack;

public Producer(SycnStack stack) {
this.stack = stack;
}

public void run() {
int i = 10;
while (i-- > 0) {
stack.push((char) (26 * Math.random() + 'A'));
Thread.yield();
}
}
}

class Consumer implements Runnable {
private SycnStack stack;

public Consumer(SycnStack stack) {
this.stack = stack;
}

public void run() {
int i = 10;
while (i-- > 0) {
stack.pop();
Thread.yield();
}
}
}


主程序:

public class ProductorConsumer {
public static void main(String[] args) {
SycnStack s = new SycnStack(5);
new Thread(new Producer(s)).start();
new Thread(new Consumer(s)).start();
}
}


That's all. thank you ...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: