public class Produce implements Runnable{
private Handler handler;
public Produce(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
for(int i = 0 ; i < 10 ; i++){
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.put(String.valueOf(i));
}
}
}
消费者:Consume
public class Consume implements Runnable{
private Handler handler;
public Consume(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
for (int i = 0 ; i < 10 ; i++){
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.eat();
}
}
}
Main:
public class Main {
public static void main(String[] args) {
Handler handler = new Handler();
Produce produce = new Produce(handler);
Consume consume = new Consume(handler);
new Thread(consume).start();
new Thread(produce).start();
new Thread(produce).start();
}
}