在Java中实现Active对象模式,可以通过创建一个包含线程池的类来实现
public class ActiveObject implements Runnable {
private final BlockingQueue<Runnable> queue;
public ActiveObject() {
this.queue = new LinkedBlockingQueue<>();
}
@Override
public void run() {
while (true) {
try {
Runnable task = queue.take();
task.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
public void addTask(Runnable task) {
try {
queue.put(task);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ActiveObjectManager {
private final ExecutorService executorService;
public ActiveObjectManager(int numberOfThreads) {
this.executorService = Executors.newFixedThreadPool(numberOfThreads);
}
public void submit(ActiveObject activeObject) {
executorService.submit(activeObject);
}
public void shutdown() {
executorService.shutdown();
}
}
public class Main {
public static void main(String[] args) {
int numberOfThreads = 4;
ActiveObjectManager manager = new ActiveObjectManager(numberOfThreads);
ActiveObject activeObject1 = new ActiveObject();
ActiveObject activeObject2 = new ActiveObject();
manager.submit(activeObject1);
manager.submit(activeObject2);
activeObject1.addTask(() -> System.out.println("Task 1 executed by ActiveObject 1"));
activeObject1.addTask(() -> System.out.println("Task 2 executed by ActiveObject 1"));
activeObject2.addTask(() -> System.out.println("Task 1 executed by ActiveObject 2"));
activeObject2.addTask(() -> System.out.println("Task 2 executed by ActiveObject 2"));
manager.shutdown();
}
}
这个示例中,我们创建了两个ActiveObject实例,并将它们提交给ActiveObjectManager。然后,我们向这些ActiveObject实例添加任务,这些任务将由线程池中的线程执行。最后,我们关闭线程池。