日期:2014-05-20 浏览次数:20771 次
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();
}
}