How to implement simple threading with a fixed number of worker threads

后端 未结 7 878
渐次进展
渐次进展 2020-12-04 06:49

I\'m looking for the simplest, most straightforward way to implement the following:

  • The main program instantiates worker threads to do a task.
  • Only
相关标签:
7条回答
  • 2020-12-04 07:42

    If you want to roll your own:

    private static final int MAX_WORKERS = n;
    private List<Worker> workers = new ArrayList<Worker>(MAX_WORKERS);
    
    private boolean roomLeft() {
        synchronized (workers) {
            return (workers.size() < MAX_WORKERS);
        }
    }
    
    private void addWorker() {
        synchronized (workers) {
            workers.add(new Worker(this));
        }
    }
    
    public void removeWorker(Worker worker) {
        synchronized (workers) {
            workers.remove(worker);
        }
    }
    
    public Example() {
        while (true) {
            if (roomLeft()) {
                addWorker();
            } 
        }
    }
    

    Where Worker is your class that extends Thread. Each worker will call this class's removeWorker method, passing itself in as a parameter, when it's finished doing it's thing.

    With that said, the Executor framework looks a lot better.

    Edit: Anyone care to explain why this is so bad, instead of just downmodding it?

    0 讨论(0)
提交回复
热议问题