您的位置:首页 > 其它

生产者消费者

2015-11-18 10:22 357 查看
class Source {
private int num = 0;
public synchronized void increase() {
while(num != 0) {
try {
wait();
} catch(Exception e) {
e.printStackTrace();
}
}
num++;
System.out.println(num);
notify();
}
public synchronized void decrease() {
while(num == 0) {
try {
wait();
} catch(Exception e) {
e.printStackTrace();
}
}
num--;
System.out.println(num);
notify();
}
}

class Producer implements Runnable{
private Source source;
Producer(Source source) {
this.source = source;
}
public void run() {
for(int i=0; i<10; i++) {
/*try {
Thread.sleep((long)Math.random()*1000);
}
catch(Exception e) {
e.printStackTrace();
}*/
source.increase();
}
}
}

class Consumer implements Runnable{
private Source source;
public Consumer(Source source) {
this.source = source;
}
public void run() {
for(int i=0; i<10; i++) {
/*try {
Thread.sleep((long)Math.random()*1000);
}
catch(Exception e) {
e.printStackTrace();
}*/
source.decrease();
}

}
}

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  生产者 消费者