中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

如何在Java中實現Active對象

小樊
87
2024-09-06 11:12:37
欄目: 編程語言

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

0
化州市| 临泽县| 衢州市| 都兰县| 宜阳县| 信宜市| 望都县| 额敏县| 株洲市| 松阳县| 攀枝花市| 闽侯县| 玛纳斯县| 珠海市| 松原市| 惠州市| 乌鲁木齐市| 敦煌市| 永年县| 红桥区| 凤城市| 巴林右旗| 江门市| 玉山县| 湖南省| 汕尾市| 临沭县| 怀宁县| 昌图县| 红河县| 祁阳县| 阳泉市| 玛纳斯县| 来凤县| 和林格尔县| 萝北县| 临潭县| 焦作市| 天水市| 两当县| 锦州市|