简体   繁体   中英

Can you run one main method on multiple threads (concurrently)?

I'm new to SO/Java software development, and I've been searching for this without much avail.

My question is --in Java-- is it possible to run one main statement across many threads at once? I am writing a native Java application in order to load test a server. The process for this is to have a bunch of threads running at once to simulate users. These threads read from a certain file, get various UIDs, manipulate some standard data, and send this to a queue on the server. After the thread sends the data, we start pulling data from the response queue, and each of the threads that have already sent their data start checking against the UID of the newly returned data, and if it matches, the process outputs the round trip time and terminates.

Algorithmic-ally, that is what I plan to implement, however I don't have much experience with concurrency and using multiple threads, so I'm not sure how I would be able to make the threads run this process. I've seen other work where an array of WorkerThreads is used, and I've read the API for Threads and read various tutorials on concurrency. Any guidance would be helpful. Thank you!

The recommended way to implement concurrent workers is to use an Executor service. The pattern is something like this:

  ExecutorService pool = Executors.newFixedThreadPool(poolSize);
  ...


  while (...) {
      final int someParameter = ...
      pool.submit(new Runnable() {
              public void run() {
                  // do something using 'someParameter'
              }
      });
  }

This approach takes care of the complicated process of creating and managing a thread pool by hand.

There are numerous variations; see the javadocs for Executors and ExecutorService .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM