Для следующего кода -< /p>
class: client < /p>
public class Client {
Integer id;
Integer priority;
}
< /code>
класс: CPU < /p>
package target2024.systemDesign.cpuProcessor;
import lombok.SneakyThrows;
import java.util.LinkedList;
import java.util.Queue;
//Singleton design pattern
public class CPU {
private static CPU instance;
private final Integer MAX_THREAD_POOL = 3;
Object lock = new Object();
static Queue executingThreadPool;
static Queue waitingThreadPool;
private CPU() {
executingThreadPool = new LinkedList();
waitingThreadPool = new LinkedList();
}
public synchronized static CPU getInstance() {
if(instance == null) {
instance = new CPU();
}
return instance;
}
@SneakyThrows
public void execute(Client client) {
System.out.println("Received client=" + client.id);
waitingThreadPool.add(client);
synchronized (lock) {
if(executingThreadPool.size() < MAX_THREAD_POOL) {
executingThreadPool.add(waitingThreadPool.poll());
} else {
lock.wait();
executingThreadPool.add(waitingThreadPool.poll());
}
}
Client clientToProcess;
synchronized (lock) {
clientToProcess = executingThreadPool.poll();
}
process(clientToProcess);
synchronized (lock) {
lock.notifyAll();
}
}
@SneakyThrows
public void process(Client client) {
System.out.println("-----Executing client=" + client.id);
Thread.sleep(1000);
}
}
< /code>
класс: cpudemo < /p>
package target2024.systemDesign.cpuProcessor;
import lombok.SneakyThrows;
public class CPUDemo {
@SneakyThrows
public static void main(String[] args) {
CPU cpu = CPU.getInstance();
int clientSize = 10;
Thread[] tarr = new Thread[clientSize];
Client[] carr = new Client[clientSize];
//Create clients
for(int i=0; i
Подробнее здесь: https://stackoverflow.com/questions/796 ... in-batches
Многопользовательское: запустить процессы партиями ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение