2024-06-10 10:53:11 +02:00
|
|
|
package actor;
|
|
|
|
|
2024-10-09 20:50:40 +02:00
|
|
|
import java.util.concurrent.LinkedBlockingQueue;
|
|
|
|
import java.util.concurrent.TimeUnit;
|
2024-06-10 10:53:11 +02:00
|
|
|
|
2024-11-03 16:18:59 +01:00
|
|
|
public abstract class ActorThread<M> extends Thread {
|
2024-10-09 20:50:40 +02:00
|
|
|
|
|
|
|
private final LinkedBlockingQueue<M> q = new LinkedBlockingQueue<>();
|
2024-06-10 10:53:11 +02:00
|
|
|
|
|
|
|
/** Called by another thread, to send a message to this thread. */
|
|
|
|
public void send(M message) {
|
2024-11-07 22:25:07 +01:00
|
|
|
String handlerName = this.getClass().getSimpleName();
|
2024-10-09 20:50:40 +02:00
|
|
|
q.offer(message);
|
2024-11-07 22:25:07 +01:00
|
|
|
System.out.println(" # Message to " + handlerName + " : " + message);
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|
2024-11-07 22:25:07 +01:00
|
|
|
|
2024-06-10 10:53:11 +02:00
|
|
|
/** Returns the first message in the queue, or blocks if none available. */
|
|
|
|
protected M receive() throws InterruptedException {
|
2024-11-07 22:25:07 +01:00
|
|
|
M mess = q.take();
|
2024-11-07 01:54:44 +01:00
|
|
|
return mess;
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|
2024-11-07 01:54:44 +01:00
|
|
|
|
2024-11-07 22:25:07 +01:00
|
|
|
/**
|
|
|
|
* Returns the first message in the queue, or blocks up to 'timeout'
|
|
|
|
* milliseconds if none available. Returns null if no message is obtained
|
|
|
|
* within 'timeout' milliseconds.
|
|
|
|
*/
|
|
|
|
@Deprecated
|
2024-06-10 10:53:11 +02:00
|
|
|
protected M receiveWithTimeout(long timeout) throws InterruptedException {
|
2024-10-09 20:50:40 +02:00
|
|
|
return q.poll(timeout, TimeUnit.MILLISECONDS);
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|
2024-10-17 01:50:25 +02:00
|
|
|
|
2024-11-07 22:25:07 +01:00
|
|
|
/** Wait for a message continuously */
|
|
|
|
protected M take() throws InterruptedException {
|
|
|
|
return q.take();
|
2024-10-17 01:50:25 +02:00
|
|
|
}
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|