java - 运行程序60分钟,每个线程使用不同的ID

标签 java multithreading threadpool executorservice

如何确保每个线程使用不同的唯一 ID,并且该 ID 应位于 startExistingRange 和 endExistingRange 之间。我很担心,因为该程序应该运行 60 分钟,而在 60 分钟之前,所有 id 可能都已被使用,那么我应该做什么。我应该重置变量吗?最佳实践是什么?

例如:- 线程 1 将使用 25,线程 2 将使用 45 等等。

class ThreadTask implements Runnable {
    private int id;

    public ThreadTask(int id) {
        this.id = id;
    }

    public void run() {
        System.out.println("Thread " + id);
    }
}

public class TestPool {

    public static void main(String[] args) {
        int size = 10;
        int durationOfRun = 60;
        int startExistingRange = 1;
        int endExistingRange = 1000;

        // create thread pool with given size
        ExecutorService service = Executors.newFixedThreadPool(size); 

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

        // Running it for 60 minutes
        while(System.currentTimeMillis() <= endTime) {
/* I want each thread uses different unique ID between startExistingRange
 and endExistingRange */
            service.submit(new ThreadTask(What should I pass 
                 here so that each thread is using different ID));
        }

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

更新:-

public class TestingPool {

    public static void main(String[] args) throws InterruptedException {
        int size = 10;
        int durationOfRun = 1;
        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);

        // Getting and releasing id in while loop
        while(System.currentTimeMillis() <= endTime) {
            Integer id = idPool.getId();
            service.submit(new ThreadTask(idPool, id));
            idPool.releaseId(id);
        }

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

}

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

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

    public synchronized Integer getId() {
        return availableIds.removeFirst();
    }

    public synchronized void releaseId(Integer id) {
        availableIds.add(id);
    }
}


class ThreadTask implements Runnable {
    private IdPool idPool;
    private int kk;

    public ThreadTask(IdPool idPool, int s) {
        this.idPool = idPool;
        this.kk = s;
    }

    public void run() {
        //Integer id = idPool.getId();
        System.out.println("Task " + kk);
        //idPool.releaseId(id);
    }
}

最佳答案

不要在创建时将 ID 传递给您的任务,而是让您的任务从可用 ID 池中获取其 ID。由于您有 10 个线程,因此只需要 10 个 ID。每个任务在启动时从池中获取一个 ID,并在完成后将其释放到池中。当然,池需要是线程安全的:

public class IdPool {
    private final LinkedList<Integer> availableIds = new LinkedList<Integer>();

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

    public synchronized Integer getId() {
        return availabeIds.removeFirst();
    }

    public synchronized void releaseId(Integer id) {
        availableIds.add(id);
    }
}


class ThreadTask implements Runnable {
    private IdPool idPool;

    public ThreadTask(IdPool idPool) {
        this.idPool = idPool;
    }

    public void run() {
        Integer id = idPool.getId();
        System.out.println("Task " + id);
        idPool.releaseId(id);
    }
}

public class Main {
    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) {
            service.submit(new ThreadTask(idPool));
        }

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

关于java - 运行程序60分钟,每个线程使用不同的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10759694/

相关文章:

Java 线程池和创建可运行对象的可运行对象

java - 用于运行 AbortableHttpRequest 的 ThreadPoolExecutor - 如何调用中止?

java - 嵌入关系

java - Gson 应为 STRING 但实际为 BEGIN_ARRAY?

java - 在Java中创建同步静态单例Map

ios - __NSArrayM objectAtIndex 崩溃,但我进行了验证

java - Log4j Commons Logging Bridge 被忽略

java - 如何在静态函数中等待多个 JavaFX 窗口的结果?

java - 线程是代码本身还是某个实体?

c# - 多次调用相同的方法并显示进度