在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實例添加任務,這些任務將由線程池中的線程執行。最后,我們關閉線程池。