Add async samples

This commit is contained in:
2018-10-24 00:18:51 +02:00
parent 8a8fa12b48
commit f656b57901
6 changed files with 27 additions and 11 deletions

View File

@ -21,7 +21,7 @@ public class App {
for (int i = 0; i < 3; i++) {
final Consumer consumer = new Consumer("Consumer_" + i, itemQueue);
executorService.submit(() -> {
while(true) {
while (true) {
consumer.consume();
}
});

View File

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
public class Consumer {
class Consumer {
private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class);
@ -13,12 +13,12 @@ public class Consumer {
private String name;
private int itemId;
public Consumer(String name, BlockingQueue<Item> itemQueue) {
Consumer(String name, BlockingQueue<Item> itemQueue) {
this.itemQueue = itemQueue;
this.name = name;
}
public void consume() throws InterruptedException {
void consume() throws InterruptedException {
final Item item = itemQueue.take();
LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, item.getId(), item.getProducer());
}

View File

@ -1,20 +1,20 @@
package threadexamples.producerconsumer;
public class Item {
class Item {
private String producer;
private int id;
public Item(String producer, int id) {
Item(String producer, int id) {
this.producer = producer;
this.id = id;
}
public String getProducer() {
String getProducer() {
return producer;
}
public int getId() {
int getId() {
return id;
}

View File

@ -3,18 +3,18 @@ package threadexamples.producerconsumer;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class Producer {
class Producer {
private BlockingQueue<Item> itemQueue;
private String name;
private int itemId;
public Producer(String name, BlockingQueue itemQueue) {
Producer(String name, BlockingQueue<Item> itemQueue) {
this.itemQueue = itemQueue;
this.name = name;
}
public void produce() throws InterruptedException {
void produce() throws InterruptedException {
itemQueue.put(new Item(name, itemId++));
Thread.sleep(new Random().nextInt(2000));
}