Threads in Java

6

I have a multi-threaded system in Java that uses the ThreadGroup class that is deprecated.

With my current implementation I also can not "kill" a thread in lock. How to implement efficient code to control Thread in Java?

I need to have minimal control over the runtime, startup, and completion of my% of threads%.

Simplified code for what needs to be done more efficiently:

int threadAtivas = 5;
ThreadGroup threadGroup = new ThreadGroup("threads");
while(true){
    if(verificaQtdThreadsAtivas(threadGroup)){
        criaNovaThread(threadGroup);
    }else{
        Thread.sleep(1000);
    }
}
    
asked by anonymous 13.03.2015 / 19:11

1 answer

1

Use ExecutorService , it is a class for thread pooling. You instantiate by saying how many threads will run concurrently, then add your Runnable to it and hope to finish.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleThreadPool {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
          // fica aqui enquanto está rodando as threads
        }
        System.out.println("Finished all threads");
    }

}
    
18.03.2015 / 19:03