首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于Java的生产者消费者有关问题

2013-08-04 
关于Java的生产者消费者问题有人能提供一下简单的Java生产者消费者模型代码吗?[解决办法]这个谷歌没有的嘛

关于Java的生产者消费者问题
有人能提供一下简单的Java生产者消费者模型代码吗?
[解决办法]
这个谷歌没有的嘛关于Java的生产者消费者有关问题
[解决办法]

public class TestThread {

public static void main(String[] args) {
Pool pool = new Pool();
Thread t1 = new ThreadIn(pool);
Thread t2 = new ThreadDe(pool);
t2.start();
t1.start();

}

}

class ThreadIn extends Thread {
private Pool pool;

public ThreadIn(Pool pool) {
this.pool = pool;
}

public void run() {
try {
for (int i = 0; i < 10; i++) {
pool.increase();
}

} catch (Exception e) {

e.printStackTrace();
}
}
}

class ThreadDe extends Thread {
private Pool pool;

public ThreadDe(Pool pool) {
this.pool = pool;
}

public void run() {
try {
for (int i = 0; i < 10; i++) {
pool.decrease();
}

} catch (Exception e) {

e.printStackTrace();
}

}
}

class Pool {
private int num = 0;

public synchronized void increase() throws Exception {

while (num > 0) {
this.wait();
}
num++;
System.out.println("num:" + num);
notify();
}

public synchronized void decrease() throws Exception {

while (0 == num) {
this.wait();
}
num--;
System.out.println("num:" + num);
notify();
}
}

热点排行