最近学习Java线程,自己写了一个非典型生产者,消费者代码,如下:
生产者类:
package com.sx.jtwait;
import java.util.Random;
public class Producers extends Thread {
private Basket basket = null;
public Producers(Basket basket) {
super();
this.basket = basket;
}
@Override
public void run() {
System.out.println("Producers start...");
while(true) {
basket.put(new Random().nextInt(5));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者类:
package com.sx.jtwait;
import java.util.Random;
public class Customer extends Thread {
private Basket basket = null;
public Customer(Basket basket) {
super();
this.basket = basket;
}
@Override
public void run() {
System.out.println("Customer start...");
while(true) {
basket.get(new Random().nextInt(5));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
篮子类:
package com.sx.jtwait;
public class Basket {
private int maxSize = 10;
private int size = 0;
public synchronized void put(int num) {
System.out.println("[put] want put:" + num + ", free size:" + (maxSize - size));
if(size + num <= maxSize) {
size += num;
System.out.println("[put] now size:" + size);
notifyAll();
} else {
System.out.println("[put] wait...");
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void get(int num) {
System.out.println("[get] want get:" + num + ", has size:" + size);
if(size - num > 0) {
size -= num;
System.out.println("[get] now size:" + size);
notifyAll();
} else {
System.out.println("[get] wait...");
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行类:
import com.sx.jtwait.Basket;
import com.sx.jtwait.Customer;
import com.sx.jtwait.Producers;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
Basket basket = new Basket();
new Customer(basket).start();
new Producers(basket).start();
}
}
运行结果:
Customer start...
[get] want get:2, has size:0
[get] wait...
Producers start...
[put] want put:4, free size:10
[put] now size:4
[get] want get:1, has size:4
[get] now size:3
[put] want put:1, free size:7
[put] now size:4
[get] want get:0, has size:4
[get] now size:4
[put] want put:3, free size:6
[put] now size:7
[get] want get:0, has size:7
[get] now size:7
[put] want put:4, free size:3
[put] wait...
[get] want get:2, has size:7
[get] now size:5
[put] want put:4, free size:5
[put] now size:9
[get] want get:2, has size:9
[get] now size:7
[put] want put:4, free size:3
[put] wait...
[get] want get:4, has size:7
[get] now size:3
[put] want put:2, free size:7
[put] now size:5
[get] want get:2, has size:5
[get] now size:3
[get] want get:4, has size:3
[get] wait...