# TicketManager.java
import java.util.Vector;
public class TicketManager {
private Vector<Worker> ticketPool = new Vector<>();
private int maxTicket;
public TicketManager(int maxTicket) {
this.maxTicket = maxTicket;
}
public boolean requestTicket(Worker worker) {
int id = worker.getId();
if (ticketPool.size() >= maxTicket) {
System.out.println("[" + id + "] 작업대기");
return false;
}
return true;
}
public void useTicket(Worker worker) {
int id = worker.getId();
if (!ticketPool.contains(worker)) {
ticketPool.add(worker);
System.out.println("[" + id + "] 작업할당");
}
}
public void releaseTicket(Worker worker) {
int id = worker.getId();
ticketPool.remove(worker);
System.out.println("[" + id + "] 작업완료");
}
}
# Worker.java
import java.util.Random;
public class Worker implements Runnable {
private TicketManager tm;
private int id;
public Worker(TicketManager tm, int id) {
this.tm = tm;
this.id = id;
}
public int getId() {
return id;
}
@Override
public void run() {
while (!tm.requestTicket(this)) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
tm.useTicket(this);
try {
System.out.println("[" + this.id + "] 작업중...");
Thread.sleep(new Random().nextInt(2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
tm.releaseTicket(this);
}
}
# Main.java
public class Main {
public static final int MAX_TICKET = 2;
public static final int MAX_WORKER = 5;
public static void main(String[] args) {
long startTime, elapsedTime = 0;
TicketManager tm = new TicketManager(MAX_TICKET);
Worker[] workers = new Worker[MAX_WORKER];
for (int i = 0; i < MAX_WORKER; i++) {
workers[i] = new Worker(tm, i);
}
startTime = System.currentTimeMillis();
ThreadGroup tg = new ThreadGroup("thread group");
for (Worker worker : workers) {
Thread t = new Thread(tg, worker);
t.start();
}
while (tg.activeCount() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("====================");
System.out.println("작업완료 " + elapsedTime + " ms");
}
}
# 결과
[0] 작업할당
[2] 작업대기
[1] 작업할당
[1] 작업중...
[3] 작업대기
[0] 작업중...
[4] 작업대기
[0] 작업완료
[2] 작업할당
[2] 작업중...
[3] 작업대기
[4] 작업대기
[1] 작업완료
[3] 작업할당
[3] 작업중...
[4] 작업할당
[4] 작업중...
[2] 작업완료
[3] 작업완료
[4] 작업완료
====================
작업완료 4001 ms
댓글 영역