Um loop de processamento multi-thread básico

No JRuby, é muito simples iniciar e gerenciar o código para ser executado em um thread, embora ainda tenha uma semântica de desligamento elegante:

# JRuby only - bring in the java.util.concurrent package
java_import java
.util.concurrent

# make a thread pool with 10 threads. This means
# we can submit any number of blocks of code to run
# but only 10 will run at a time.
service
= Executors.new_fixed_thread_pool(10)

# shutdown our ExecutorService when someone kills us
signal
.trap('SIGINT') { service.shutdown }

loop
do
work
= get_some_work
service
.execute { do_some(work }
# if someone shut us down, break out of the loop
break if service.is_shutdown
end
# at this point, we aren't taking new work, but we
# might have more work in progress or scheduled.
# Let's wait a bit for them to finish:
service
.await_termination(10,TimeUnit.SECONDS)

# once we get here, we've either waited 10 seconds, or
# everyone has finished working. Either way, time to go:
service
.shutdown_now

Os motivos para usar um pool de threads por meio do ExecutorServiceé limitar o número de threads reais em andamento. Adicionar encadeamentos tem um custo e, se adicionarmos muitos, perderemos os benefícios obtidos com um ambiente multi-encadeamento. Certifique-se de que, em vez de usar um literal como eu fiz (10), use um valor configurável que você possa facilmente ajustar na produção.