Here is what I want to do:
There are many threads start at any time, and each thread will run about 5s. When one thread is running, others must wait. And when the running thread ends, the newest thread start to run and other waiting threads just stop.
Of course, there will be situations: when one thread start, there's no other thread.
I tried to use FutureTask, but failed. It seems too complex for me.
Can anyone give me some idea?
you might want to take a look at single-threaded executor, which will take your tasks from task queue and invoke them sequentially.
it is more convenient to use this class if you will decide later to add some concurrency
Related
I have a thread pool created from ThreadPoolTaskExecutor:
threadPoolTaskExecutor.setCorePoolSize(10);
this ThreadPoolTaskExecutor will execute runnables, each runnable has a Thread.sleep(6000); call during the task execution.
So when I execute the 1st task and when the 1st task calls Thread.sleep(6000) to sleep, at that time, execute the 2nd task, will it be possible the 2nd task will use the thread of the 1st task or interrupt the thread used by the 1st task? since it is in sleep.
No, not automatically. If a normal Java Thread is sleeping, then it's sleeping.
Also, Threads are really cheap nowadays, I would not bother with details like that.
Working around the sleep and let that 'sleeping' Thread do some other work is really really hard to manage properly and easily will lead to loads and loads of unforeseen problems.
In your situation, what you COULD improve is that the pool size is not fixed but dynamic, releasing (destroying) threads when they haven't been used for some time (say: a minute).
If more threads are needed, the pool will create new Threads, up to the given limit. (Executors.newCachedThreadPool())
That's especially helpful on a server, because 99% of threads on there are just idle (not even 'actively' sleeping).
Here are some details that might interest you: https://www.baeldung.com/thread-pool-java-and-guava
Especially check out ForkJoinPool: https://www.baeldung.com/java-fork-join, because this comes very close to a very similar problem.
I want to achieve what Platform.runLater() does but on the current thread and the program isn't related to JavaFX, it's a Tomcat server.
I tried to do Platform.runLater(this::foo); but I'm pretty sure it doesn't do anything. Probably because there's no JavaFX thread to do it.
I'd rather not open a ScheduledExecutorService because it's going to be another thread on many instances (so many threads), not to mention the method it would need to run is synchronized so I smell a deadlock.
I couldn't find any useful methods on Thread.currentThread() (run and start don't take parameters).
Is there another option to do this?
I used a newSingleThreadExecutor to achieve this, since it can take multiple runnables to a queue and run them sequentially, it can be given tasks from several places and it will run them one by one, it's similar to platform.runLater.
Having a single thread that all instances of the class hold a reference to, solves the "many threads" problem.
It also won't cause a deadlock because it will at most wait for just one other thread to finish the synchronized function and then run just this one function.
I have only two short-lived tasks to run in the background upon the start of the application. Would it make sense to use a thread for each task or an Executor, for instance, a single thread executor to submit these two tasks.
Does it make sense to create two threads that die quickly as opposed to having a single threaded executor waiting for tasks throughout the lifecycle of the application when there are none?
One big benefit of using a threadpool is that you avoid the scenario where you have some task that you perform repeatedly then, if something goes wrong with that task that causes the thread to hang, you're at risk of losing a thread every time the task happens, resulting in running the application out of threads. If your threads only run once on startup then it seems likely that risk wouldn't apply to your case.
You could still use Executor, but shut it down once your tasks have both run. It might be preferable to use Futures or a CompletionService over raw threads.
If you do this more than once in your application, ThreadPoolExecutor is definitely worth a look.
One benefit is the pooling of threads. This releaves the runtime to create and destroy OS objects every time you need a thread. Additionally you get control of the amount of threads spawned - but this seems not the big issue for you - and threads running/done.
But if you actually really only spawn two threads over the runtime of your application, the executors may be oversized, but they are nevertheless very comfortable to work with.
Since Nathan added Futures, there is also Timer and TimerTask. Also very convenient for "Fire and Forget" type of background action :-).
I have a Thread that needs to continuously run, however when a certain action is called, I want to wait 500ms, and then do another action, without interrupting the main Thread. Is there any way to do so?
I immediately thought of creating an just restarting a new Thread each time, but this doesn't seem to work.
EDIT: There seems to be a confusion with the question, so let me elaborate. I have a thread that is contiously working. When and action is preformed, a method is called. In that method I need to wait for 500ms and then call another method, without interrupting the main thread. This also has to be re-usable.
Quartz is an scheduler that allows you to:
... create simple or complex schedules for executing tens, hundreds,
or even tens-of-thousands of jobs; jobs whose tasks are defined as
standard Java components that may execute virtually anything you may
program them to do. The Quartz Scheduler includes many
enterprise-class features, such as support for JTA transactions and
clustering.
You can implement scheduled jobs to run in a certain given time. Here you can find some tutorials and more info:
http://quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/
This might give you the idea of how to handle similar situations:
How to Pause and Resume a Thread in Java from another Thread
and excuse the lack of knowledge on multithreaded apps, but I am new to the field.
Is there a pattern or common used methodology for monitoring the 'job completion' or 'job status' of worker threads from a monitor (a class that acts as a monitor)?
What I have currently done is create a list of workers and create one thread for each worker. After all threads have started i am looping over the worker list and 'checking their status' by making a call to a method.
At that time I couldn't come up with a different solution, but being new to the field, I don't know if this is the way to go, or if there are other solutions or patterns that I should study.
Depending on what you want, there are many ways that you can do this.
If you just want to wait until all the threads finish (i.e. all you care about is having everything finish before moving on), you can use Thread.join():
try {
for (Thread t: threadsIWaitOn)
t.join();
} catch (InterruptedException iex) {
/* ... handle error ...
}
If you want a more fine-grained control over the thread status and want to be able, at any time, to know what threads are doing, you can use the Thread.getState() function. This returns a Thread.State object that describes whether the thread is running, blocked, new, etc., and the Javadoc specifically says that it's designed for monitoring the state of a thread rather than trying to synchronize on it. This might be want you want to do.
If you want even more information than that - say, how to get a progress indicator for each thread that counts up from 0 to 100 as the thread progresses - then another option might be to create a Map from Threads to AtomicIntegers associating each thread with a counter, then pass the AtomicInteger into the constructor of each thread. That way, each thread can continuously increment the counters, and you can have another thread that continuously polls the progress.
In short, you have a lot of options based on what it is that you're trying to accomplish. Hopefully something in here helps out!
Use a ThreadPool and Executor, then you get a Future<> and you can poll for their completion and some more nice stuff, too. I can appreciate this book for you: Java Concurrency in Practice
Try to use any kind of synchronization. For example, wait on some kind of monitor/semaphore until job is done / whatever you need.