There are 3 threads: Main Thread (thread from which main() runs on), Thread A and Thread B.
Order of Operations:
Program Starts (main())
Main Thread instantiates and starts Thread A.
Thread A after X seconds instantiates Thread B.
Thread B is started.
Thread B after X seconds instantiates Thread A.
Thread A is started.
If the call to Thread B is the LAST statement executed in the runnable of Thread A, will Thread A terminate after Thread B is instantiated and started? Or will Thread B be nested in Thread A and therefore create an infinite number of nested threads? What is the default behaviour and how would I accomplish NOT creating an infinite number of threads (I would like every previous thread to end while the child survives).
A Thread.join() would cause the thread to wait until the children thread die, correct?
If this is just bad practice in general, can anyone recommend alternatives that will essentially accomplish the same task? I need one function to, after a few seconds, call another functions which will then run simultaneously with the first function. The first function will then, after completing some commands, die. The second function should then, after a few seconds, call a new instance of the first function. This loop should continue until aborted by the main thread (or until the program exits).
Your question contains the answer: you are thinking of threads as tasks or "functions to run", which they are not. Threads execute tasks, so design your code around the idea of tasks that can create other tasks. Tasks are simply Objects that implement the Runnable interface, nothing more. You can construct these tasks (or runnable objects) with all the data they need, even including references to other (parent) tasks.
Create one CachedThreadPool and whenever a task is ready to be executed, dump the task in the threadpool using the execute method.
One thing you will need to consider is program shutdown: you need to close the ThreadPool in order to close your program gracefully. You can simply call shutdownNow, but you'll probably want to device a technique that gives important tasks a chance to complete and then shutdown. That will take some practice to get it right (shutdownHooks for example are not easy), but from then on you can re-use it whenever you need more than 1 thread.
Related
I'm learning executor service in java.
Requirement is using executor service create 4 threads -
Thread 1 - get two numbers as input.
Thread 2 - addition of two numbers
Thread 3 - multiplication of two numbers
Thread 4 - print the results.
Thread 1 should be executed first, after thread 1 is complete thread 2, 3 can start processing simultaneously and finally once thread 2, 3 is completed. Thread 4 should run finally.
How can we make sure which thread starts first and which threads to start simultaneously next. Finally which thread to execute at last.
Note: How can we achieve this without using thread sleep. Dynamically as soon as thread 1 finishes other two threads should start automatically.
First, Read my comment on your original question--the one about using a car to hammer in nails.
Ok, Now, #dan1st had some ideas about how to structure the solution. Here's two more.
Use a global int variable, a global lock, and wait() and notifyAll(): Have each thread enter a synchronized(lock) block in which it
Loops, calling lock.wait() until the global int has some particular value,
Does its trick,
Sets the global int to the value that will trigger the next thread,
calls lock.notify(), and finally
exits
Use Semaphores: Pass two Semaphore instances in to each thread. Call them in and out or some such names. Have each thread
wait its turn by calling in.acquire(),
do its trick,
call out.release(),
and then exit.
Your main routine then is responsible for creating the semaphores, and passing them to the new threads in such a way that each thread's out refers to the same semaphore as the in of the thread that is expected to perform the subsequent task.
IMO, option 2 is more elegant, because if your teacher asks you next week to modify your program by adding another step in the middle of the sequence, then none of the existing tasks that you wrote will have to change at all. You'll only need to write the new task and change two or three lines in the main() routine.
Doesn't sound like much of an improvement, and option 2 clearly is more work to set up in the first place than option 1, but if you ever are employed to work on enterprise-scale software systems with millions of lines of code, you will come to appreciate the beauty of option 2.
You could do this using multiple ways.
For exanple, joining:
A Thread can join another Thread, which means that it waits until the other Thread finishes. Thread 2 and 3 could join Thread 1 and Thread 4 could join Thread 2 and 3.
Another possibility is await and signal but I am not sure if it meets your Requirements(it uses something similar to Thread.sleep():
At first, you create a common java.util.concurrent.locks.Lock and create a condition of this lock with .newCondition() You also create a second condition using newCondition().
The lock has to be locked before calling await and signal/signalAll.
Thread 2 and 3 calls .await() on the first condition before starting and Thread 1 calls .signalAll on the first condition when it finishes.
Thread 4 calls .await() on the second condition before it starts.
The Thread (either 2 or 3) that finishes last(the logic which Thread finished first should be synchronized with the lock) calls .signal() on the second condition.
The threads could also start each other:
Thread 1 starts Thread 2 and 3 after it's task finishes but I would recommand you one of the other mechanisms for Thread 4.
[DISCLAIMER]
You may not be able to interact with the Threads directly if you use an ExecutorService. This post might help you with joining, await/signal should not be more difficult and the Threads can also schedule a task to the thread pool if needed.
In my main method i have started 1 daemon thread which runs in background to check certain condition is satisfied, if satisfied then my main thread should wait for sometime and then continue.
Is it possible to do so? Controlling Main thread from another thread.
Actually am trying to automate 1 application where there are many pop-up windows displayed and I want to use 1 thread in background to check for pop-ups, if pop-ups are displayed then my main method should wait for some time then begin again.
You can simply use the wait() and notify() on a common lock object.
From inside the main method, syncronize on the lock object. Within the synchronized block start your another thread and invoke wait() on the lock object.
In the run method of your second thread , write a synchronized block on the lock object and do your processing. Once it is done you can invoke the notify on the same lock object.
Main thread can then check if the required state has been set and then further actions can be decided (if you wish the main thread to complete its execution further or again wait and let second thread again do the processing) If you wish the second thread to again do (retry) the processing then like above you can invoke the notify() on the lock object and then can then invoke wait() on the same lock object.
This is the usual way of communication between two threads. But if its only single time process and you do not want it to happen multiple times then you can simply use the join() method. Main thread can join on the second thread. Till the second thread will be processing its task the main thread will be waiting for the processing to complete. Once the second thread is executed completely (end of run () method) control will reach the maim thread.
I suggest you to have a look at these methods. consumer-producer is a famous problem to understand these methods. You can also see these in action in an answer to another post.
https://stackoverflow.com/a/42049397/504133
i've got an application with a possible number of threads. basicly the threads should work this:
Main Thread
CalculationThread
CalculationThread
CalculationThread
Adding / Executing those threads to a FixedThreadPool isn't the problem. The Thread itself calls a certain function in the Mainthread to submit the results. After this step, the thread should sleep until it will be called again for the next calucation.
The Mainthread holds a reference to a CalculationThread to submit updates to the thread and readd it to the pool to start the next calculation.
My Problem: How can I enforce a timeout for a certain thread? The enforcement of this timeout must also work, if a endless loop occurs
You cannot enforce the timeout without cooperation from the thread, at least not in a sane way. You should code your calculation tasks so that they comply with the Java interruption mechanism. Basically, that means occasionally checking the Thread.interrupted return value and aborting on true.
The only other option is the ham-handed – and deprecated – Thread.stop, which can wreak general chaos, especially when done on a pool-managed thread.
Trying to wrap my head around Java concurrency and am having a tough time understanding the relationship between thread pools, threads, and the runnable "tasks" they are executing.
If I create a thread pool with, say, 10 threads, then do I have to pass the same task to each thread in the pool, or are the pooled threads literally just task-agnostic "worker drones" available to execute any task?
Either way, how does an Executor/ExecutorService assign the right task to the right thread?
Typically, thread pools are implemented with one producer-consumer queue that all of the pool threads wait on for tasks. The Executor does not have to assign tasks, all it has to do is push them onto the queue. Some thread, a 'task-agnostic worker drone', will pop the task, execute its 'run()' method and, when complete, loop round to wait on the queue again for more work.
If I create a thread pool with, say, 10 threads, then do I have to pass the same task to each thread in the pool, or are the pooled threads literally just task-agnostic "worker drones" available to execute any task?
More or less the latter. Any given task gets assigned to the next available thread.
Either way, how does an Executor/ExecutorService assign the right task to the right thread?
There is no such thing as the "right" thread. The task (i.e. the Runnable) needs to be designed so that it doesn't matter which thread runs it. This is not normally an issue ... assuming that your application properly synchronizes access / updates to data that is potentially used by more than one threads.
This question already has answers here:
termination of program on main thread exit?
(2 answers)
Closed 7 years ago.
will main thread exit before child threads complete execution?
i read in 2 articles
http://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-management.html
in the above article, In "Thread Termination" para, it states in Red " if the parent thread terminates, all of its child threads terminate as well."
http://www.roseindia.net/java/thread/overview-of-thread.shtml
in the above article, the last line in that page states "The main() method execution can finish, but the program will keep running until the all threads have complete its execution.".
i fee they are contradictory. if i am wrong, Please experts correct me.
In my program, a program with Main method calls the constructor of 2 threads . in the constructor of the respective threads, i am having the start() method .
TestA A = new TestA("TestA");
TestB B = new TestB("TestB");
public TestA(String name) {
System.out.println(name);
t = new Thread(this);
t.start();
}
i would like to know what happens, main thread terminates before child threads complete execution? if so, will the child threads anyway, continue their execution??
i tried running the program, some times all the child threads are getting executed complete even if the main thread exits.
In the 2 threads , i am processing some files. in testA thread A alone, 1 file alone is not getting processed some times. but many times, all the files are getting processed and i do not have any issues.
Java makes a distinction between a user thread and another type of thread known as a daemon thread. The difference between these two types of threads is that if the JVM determines that the only threads running in an application are daemon threads (i.e., there are no user threads), the Java runtime closes down the application. On the other hand, if at least one user thread is alive, the Java runtime won't terminate your application.
When your main() method initially receives control from the Java runtime, it executes in the context of a user thread. As long as the main-method thread or any other user thread remains alive, your application will continue to execute.
In your case, the threads are user threads and hence are allowed to complete before the main thread exits.
i am processing some files. in testA thread A alone, 1 file alone is
not getting processed some times. but many times
The reason for the above is could be something else than thread exits. It could be file locks, synchronization issue etc.
Thread (Java SE 10 & JDK 10):
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
The background threads will keep running, even if the MAIN thread completes.
If you want MAIN to stop them (example, when MAIN is complete), have your MAIN set a "keep running" flag variable (which you must set as "volatile"), which the threads occasionally look at. MAIN sets it to false (variable) or null (object) when MAIN wants to stop them. When it's false or null, then the thread must "return;".
This is somewhat complex to implement, there are many ways, but easiest is to make your Runnable an inner class, so that your Runnable has easy sharing of the flag.
For the best implementations, look up this technique in Java applets' start/stop routines.
Once the main thread exits, it takes the children with it. Perhaps by "finish" the second article simply means no more operation other than waiting for the children. Once the main thread calls System.exit(0); it's over -- every body dies.
Say you have two threads running: threadA and threadB. in the main method. The first code is the nice way of terminating the thread -- just one of many ways:
threadA.start();
threadB.start();
final long intercept = 300;
long startTime = System.currentTimeMillis();
while (threadA.isAlive() && mis.isAlive()) {
threadA.join(intercept);
if (System.currentTimeMillis() - startTime > intercept) {
threadB.interrupt();
threadA.interrupt();
threadA.join();
}
}
System.exit(0);
Below is an abrupt way of killing all threads from within main:
System.exit(0);