Thread Control in Java

Asked

Viewed 1,253 times

6

I have a multi thread Java system that uses the class ThreadGroup which is deprecated.

With my current implementation I can’t "kill" a thread in lock either. How to implement efficient code for Thread in Java?

I need to have at least control over the execution time, startup and completion of my Pool threaded.

Simplified code of what I need to do more efficiently:

int threadAtivas = 5;
ThreadGroup threadGroup = new ThreadGroup("threads");
while(true){
    if(verificaQtdThreadsAtivas(threadGroup)){
        criaNovaThread(threadGroup);
    }else{
        Thread.sleep(1000);
    }
}
  • Related: http://answall.com/q/45320/132

  • Can you give more details explaining better what this pool consists of? How it is instantiated and how you use it?

  • I improved the question with an example code.

  • 1

    Your code example is not good, after all the variable threadGroup It’s not being used anywhere, so the simplest suggestion, but which probably serves no purpose in practice, would simply remove the second line of it. In addition to the Thread.sleep(1000) spear one InterruptedException. This exception is fundamental to answer your question, and therefore how you are treating it?

  • I have completed the example. I am not treating the InterruptedException, how I should treat?

1 answer

1

Use the ExecutorService, it’s a class for threads pool. You instantiate how many threads will run simultaneously, then add your Runnable in it and hopes to end.

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");
    }

}
  • The shutdown() method will set a flag to interrupt threads in progress.

  • Won’t interrupt the threads, WITHOUT the shutdown He’s waiting for you to send more Runnable pro ExecutorService (keeps the pool in memory), WITH the shutdown he will not accept the addition of any more Runnable and as the threads are finishing it takes out of memory the allocated pool space.

  • Without the shutdown your threads continued in stopped memory; However when leaving the state runnable will release the pool of ExecutorService, about this there is no doubt, but if Voce calls the shutdown before the end of the execution of a thread, it will not set a flag on all threads to interrupt?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.