Add async samples
This commit is contained in:
parent
8a8fa12b48
commit
f656b57901
15
async/pom.xml
Normal file
15
async/pom.xml
Normal file
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>java-cookbook</artifactId>
|
||||
<groupId>fr.gasser</groupId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>async</artifactId>
|
||||
|
||||
|
||||
</project>
|
@ -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());
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
|
@ -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));
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user