0

以下のコードを 60 分間実行しています。実行しているのは、コマンドに Previous があるかどうかに基づいて、各スレッドが異なる一意の ID を使用することです。前の場合は、1 から 1000 の間の既存の ID を使用し、前の場合でない場合は、5000 から 10000 の間の一意の ID を使用します。コマンドが前の場合、各スレッドは一意の ID を使用するこのコードを書きました。 ID は 1 から 1000 の間で、Previous でない場合は 5000 から 10000 の間の一意の ID を使用します。

したがって、問題のステートメントは次のようになります。コマンドに Previous がある場合、各スレッドは 1 ~ 1000 の一意の ID を使用し、Previous でない場合、各スレッドは 5000 ~ 10000 の一意の ID を使用します。

私の質問は- 1) これは正しい方法ですか? または、何が最善の方法であるか 2) 第二に、これは非常に遅く、時々停止し、それらの番号の間に一意の ID を使用しません。IDが終了した場合もIDを再利用する必要があります

class IdPool {
    private final LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
    private final LinkedList<Integer> availableNewIds = new LinkedList<Integer>();

    public IdPool() {
        for (int i = 1; i <= 1000; i++) {
            availableExistingIds.add(i);
        }

        for (int k = 5000; k <=10000; k++) {
            availableNewIds.add(k);
        }
    }

    public synchronized Integer getNewId() {
        return availableNewIds.removeFirst();
    }

    public synchronized void releaseNewId(Integer id) {
        availableNewIds.add(id);
    }

    public synchronized Integer getExistingId() {
        return availableExistingIds.removeFirst();
    }

    public synchronized void releaseExistingId(Integer id) {
        availableExistingIds.add(id);
    }
}


class ThreadNewTask implements Runnable {
    private IdPool idPool;
    private Command command;

    public ThreadNewTask(IdPool idPool, Command cmd) {
        this.idPool = idPool;
        this.command = cmd;
    }

    public void run() {
        if(command.getDataCriteria().equals("Previous")) {
            Integer id = idPool.getExistingId();
            newMethod(id);
            idPool.releaseExistingId(id);
        } else {
            Integer newId = idPool.getNewId();
            newMethod(newId);
            idPool.releaseExistingId(newId);
        }

    }

    private void newMethod(Integer i) {
        System.out.println("Task ID: " +i);

    }
}

public class TestingPool {
    public static void main(String[] args) throws InterruptedException {
        int size = 10;
        int durationOfRun = 60;
        IdPool idPool = new IdPool();   
        // create thread pool with given size
        ExecutorService service = Executors.newFixedThreadPool(size); 

        // queue some tasks
        long startTime = System.currentTimeMillis();
        long endTime = startTime + (durationOfRun * 60 * 1000L);

        // Running it for 60 minutes
        while(System.currentTimeMillis() <= endTime) {
            Command nextCommand = getNextCommandToExecute();
            service.submit(new ThreadNewTask(idPool, nextCommand));
        }

        // wait for termination        
        service.shutdown();
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); 
    }
}
4

0 に答える 0