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

后端 未结 7 901
渐次进展
渐次进展 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条回答
  •  旧时难觅i
    2020-12-04 07:25

    /* Get an executor service that will run a maximum of 5 threads at a time: */
    ExecutorService exec = Executors.newFixedThreadPool(5);
    /* For all the 100 tasks to be done altogether... */
    for (int i = 0; i < 100; i++) {
        /* ...execute the task to run concurrently as a runnable: */
        exec.execute(new Runnable() {
            public void run() {
                /* do the work to be done in its own thread */
                System.out.println("Running in: " + Thread.currentThread());
            }
        });
    }
    /* Tell the executor that after these 100 steps above, we will be done: */
    exec.shutdown();
    try {
        /* The tasks are now running concurrently. We wait until all work is done, 
         * with a timeout of 50 seconds: */
        boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);
        /* If the execution timed out, false is returned: */
        System.out.println("All done: " + b);
    } catch (InterruptedException e) { e.printStackTrace(); }
    

提交回复
热议问题