如何在Java中实现Active对象

avatar
作者
猴君
阅读量:0

在Java中实现Active对象模式,可以通过创建一个包含线程池的类来实现

  1. 首先,创建一个实现Runnable接口的ActiveObject类:
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();         }     } } 
  1. 创建一个包含线程池的ActiveObjectManager类:
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();     } } 
  1. 使用ActiveObject和ActiveObjectManager:
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实例添加任务,这些任务将由线程池中的线程执行。最后,我们关闭线程池。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!