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

后端 未结 7 882
渐次进展
渐次进展 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:33

    As others here have mentioned, your best bet is to make a thread pool with the Executors class:

    However, if you want to roll your own, this code should give you an idea how to proceed. Basically, just add every new thread to a thread group and make sure that you never have more than N active threads in the group:

    Task[] tasks = getTasks(); // array of tasks to complete
    ThreadGroup group = new ThreadGroup();
    int i=0;
    while( i0 ) {
        if( group.activeCount()

提交回复
热议问题