Using Thread.interrupt () will not stop the thread from starting, it just sends you a signal. It is our job to listen to this signal and act accordingly.
Thread t = new Thread(new Runnable(){ public void run(){
But instead of doing all this work, consider using an ExecutorService. You can use the Executors class with static methods to return various thread pools.
Executors.newFixedThreadPool (10)
- creates a fixed pool of threads of size 10 and more jobs will be sent to the queue for further processing
Executors.newCachedThreadPool ()
- starts with 0 threads and creates new threads and adds them to the pool on the required basis if all existing threads are busy with some task. It has a termination strategy which, if a thread is idle for 60 seconds, will remove this thread from the pool
Executors.newSingleThreadExecutor ()
- creates one thread that will be loaded from the queue, all tasks that were sent will be processed one by one.
You can submit the same Runnable tasks to the thread pool. Artists also have methods for receiving pools to which you can send scheduled tasks, what do you want in the future
ExecutorService service = Executors.newFixedThreadPool(10); service.execute(myRunnableTask);
Approaching your question, when you use thread pools, you have the option to disable them after some time has passed as
service.shutdown(); service.awaitTermination(60, TimeUnit.MINUTES);
A little to pay attention to
shutdown () Starts an orderly shutdown in which previously assigned tasks are executed, but new tasks will not be accepted. A call has no additional effect if it is already turned off.
awaitTermination () waits until the state of the worker goes to TERMINATED. But first, the state should go to SHUTDOWN if shutdown () is called, or STOP if shutdownNow () is called.
Arkantos
source share