Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have got a problem, lets say i have got code like that:
public static void main(String[] args)
{
startMethod1();
startMethod2();
}
Now, if startMethod1 method is very big and takes a lot of time to execute it, startMethod2 is started before startMethod1 has been finished.
How to make those methods execute 1 by 1?
startMethod2 is started before startMethod1 has been finished.
This will never happen. You can start threads in startMethod1 which could still be running as startmethod2 starts. startMethod2 cannot start before startMethod1 unless startMethod1 calls startMethod2
If you want to wait until the threads in startmethod1 have finished you have to Thread.join() them or use ExecutorService.awaitTermination()
How to make those methods execute 1 by 1?
Just as you have written the code.
They already do. The way you've written it, startMethod2 will not start until startMethod1 runs.
If you are using Threads then please change your code-example... but i pretend that you did, because your comment on another question showed that you meant to ;-)
You might take a look at wait() and notify()
Call wait() to tell the current Thread to suspend, and notify() to wake it up again
My guess is that you're using some kind of message logging API which is buffering, and hence some output is appearing much later than you expect. Possibly not even flushing until the end of the program. Hence you're getting interleaved output which is misleading you.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
Many times I have seen that in some sample solutions, if it said stop the thread every second, the creator did something like this, in the run method:
while(true){
try{
sleep(1000);
}catch{...}
//And following everything inside, what the run method should execute
}
So in a while loop that executes infinitely.
Otherwise, I have also seen this:
//codethat should be executed
try{
sleep(1000);
}catch{...}
//(Without while loop, only in try catch block)
Why sometimes they put the sleep method in a loop, and sometimes not?
In some solutions, where the creator of the code put sleep in a loop and then I removed the loop, the code stopped working. In other cases where it was not in a loop, and I put it in a loop, the code resulted in errors.... Why?
How can I know when I have to put it in a loop?
In these sample codes, sleep is mainly used to demonstrate a simulation who threads are working parallelly. If sleep is not used, then we won't be able differentiate if the code running in main thread or other thread.
Also putting the sleep inside makes the thread wait for 1 sec and executes the code thereafter for infinite period. The thread will not terminate and run for infinite period doing the same thing at regular interval. But when loop is not used, the code is only ran once and the thread waits for 1 sec and terminates. So it is mainly about the other piece of code doing.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a problem I've been stuck on for a day now. I am implementing a test using threads. I cannot post the code here because it's confidential but I can give you the structure:
class Something{
String error = "";
Listener listener = new Listener{
onError{
error = "something";
}
...
create some threads
start threads
The code in each thread may or may not give error, therefor modifying the error. My concern is that, having multiple threads, it will "confuse" the listener.
Attention: the listener is not for the threads themselves (doesn't listen if the thread stop or stuff like that). The listener was implemented independent from the threads but I do need it.
Help is much appreciate it. Ask any questions if not clear.
I assume that by "confuse the listener" you are talking about errors that you may get due to the listener being called from multiple threads. Just make sure that the listener is "thread-safe" and can be called from multiple threads. For instance, a listener that interacts with a variable or structure without locking out other threads may be a problem if multiple threads try to change the same structure concurrently.
If the method only deals with local variables or member/global variables that are locked for concurrency, you should not have an issue. It is hard to provide specific advice without knowing the code which you cannot share.
Search online for "thread-safe" for Java and Android and you should find some useful information. What you are trying to do is not unusual or weird: It is common practice, but you must take care.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Just say I have 4 methods from two different classes.. class1.method1(), class1.method2(), class2.method3(),class2.method4().
method1 will be streaming data to a database which can take a few minutes to execute.
method2 will use the data in the database to generate a text file.
How can I program the start point of the program to run method1() first when it has completed run method2() and so on.
I have looked into threads which I just seem to be looking at timing sleep methods. Anyone have a solution to this? if i run the code as it is then it results in method2 being executed while data is STILL being streamed into database so I need it to wait until method1 has stopped.
//start point for program
public static void main(String[]args){
//run first until all data is inputted into database
class1.method1();
//then run next method until completed
class1.method2();
//so on..
Keep it simple.
Java code runs statement by statement, unless you tell it otherwise using threads &c.
(Formally the Java interpreter is allowed to reorder statements as an optimisation strategy but only if there are no side effects).
maybe I don't understand the question, java acting like you need.
As you write, first is executed method1, when is totally completed is executed method2 an so on.
By default methods are blocked aslong as they dont run in a different Thread. If you want to have Threaded method calls (which i guess that you are looking for) then you need to sync them. Else Java will run statement by statement.
It already does what you want it to do.
Here:
public static void main(String[]args){
class1.method1(); // this will run first until it totally gets completed
class1.method2(); // Now this method will run
}
As in java everything gets executed statement by statement and thats what your code is doing.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I generally write most of my code without worrying about threading and such, and get it working and debugged before trying to offload pieces to other threads. For me, the simplest way to do it is to break the function down into a Runnable or two. From there I can start a piece via new Thread(runnable).start() and other pieces I start on the main thread via handler.post().
The problem is that I can't pass arguments. I can sometimes get around this, but too often I end up using non-local variables, which makes things a real mess. Any ideas on the "correct" way to pass arguments to a runnable?
I usually create a new class implementing Runnable and pass arguments as constructor parameters and store them in final fields.
If I need a result back from computation I implement Callable instead.
I am also using executors rather than threads directly.
Definitely a public synchronized queue.
Create a global queue of data to process, in order, and then use that queue to access external variables/data. Create a method to add data to the queue, and then one to get the last element and shift it.
This ensures that the data gets across to your thread from an external thread, such as the main program thread, without interrupting the program flow.
The queue can be processed by adding value when data needs to be passed, and the get last element method can be called to get the last date element passed to the thread.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a custom business requirement. I need to execute a series of service calls. Each of these call creates a new record in the database. I need to execute the next service call only after the previous service call has finished, because the new service call will use the record created in the DB by previous service call, as a input parameter.
I had decided to wrap each of these service calls in a Future Tasks and then use Executors.newSingleThreadExecutor() to execute these tasks in a loop.
Please suggest will it suffice and a better solution if it will not ??
Also do I need to place task.isDone() before executing the next task??
I have decided to use Executors.newSingleThreadExecutor().
Good choice given your requirement.
Please suggest will it suffice and a better solution if it will not ??
Yes, pretty much so. With the standard JDK libraries, this is probably the best you can find.
Also do I need to place task.isDone() before executing the next task??
No. The javadoc for this executor explicitly states that "[...]Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time."
Therefore, no task will be initiated before the previously active one terminates (successfully or not). Just stuff them into the executor, it will handle things for you.