-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerThread.java
More file actions
45 lines (38 loc) · 1.58 KB
/
Copy pathProducerThread.java
File metadata and controls
45 lines (38 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class ProducerThread extends Thread {
private static final AtomicInteger ID_COUNTER = new AtomicInteger(1);
private final BlockingQueue<Order> queue;
private final int ordersToGenerate;
private final Random random = new Random();
public ProducerThread(BlockingQueue<Order> queue, String name, int ordersToGenerate) {
super(name);
this.queue = queue;
this.ordersToGenerate = ordersToGenerate;
}
@Override
public void run() {
for (int i = 0; i < ordersToGenerate; i++) {
int seqId = ID_COUNTER.getAndIncrement();
int roll = random.nextInt(10);
Order order;
if (roll < 8) { // 80% BUY/SELL
Order.Side side = (roll < 4) ? Order.Side.BUY : Order.Side.SELL;
double price = 100.0 + (random.nextDouble() * 4);
int qty = 1 + random.nextInt(100);
order = new Order(seqId, side, price, qty, -1);
} else { // 20% CANCEL
int cancelTarget = Math.max(1, seqId - random.nextInt(50));
order = new Order(seqId, Order.Side.CANCEL, 0, 0, cancelTarget);
}
try {
queue.put(order);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
System.out.println("[" + getName() + "] Done.");
}
}