I want to create a class that IS A TimerTask and also a Thread. I am assuming that there is nothing wrong with this idea. The reason why I am doing it is mentioned in the "desired output" section of my post here.
Java class CANNOT inherit from two classes. So, how do I fix this problem?
The reason is in the post i mentioned in my question.
Actual output:
All timer tasks are executed in the main method. My main code's last print statement is displayed before all the timer tasks are executed. I don't want that.
Expected output:
I want the end print statement of main to come after everything else.
Extend TimerTask and Implement Runnable
Edit made after restating original problem: Check https://stackoverflow.com/a/4951059/869488
You're asking the wrong question. Multiple inheritance isn't possible in Java, but that's not your actual goal.
What you want is the ability to wait for multiple timed tasks to finish. There are a few ways of achieving that.
Probably the most straightforward is using a ScheduledExecutionService, which will give you a Future that you can wait on, in a way similar to the join method you're used to.
Another way would be to use a CountDownLatch to have each timer task decrement the latch when it is done; you can then wait for them to finish by using await.
Yet another is the strategy of using the wait and notify primitives to build the synchronization yourself – your problem isn't hard to address this way, either.
The design you want is not supported by Java.
A supported design is to use wait and notify instead of joining to the TimerTask thread (which you can't do). Examples here under this SO question: A good small example to demonstrate wait() and notify() method in java
You can implement Runnable.
class BulbJob extends TimerTask implements Runnable
{
public void run()
{
}
}
Related
Usually to start a thread we either extend the Thread class or implements Runnable interface and override run() method. But in the code below we are not doing any of above and in fact it is using anonymous class to create a thread. Is it really a good/legal/advisable way to start a thread in java?
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
}
});
thread.start();
Is it really a good/legal/advisable way to start a thread in java?
good? -
whether its good depends on your requirements, if you need a thread to run some heavy function in a kind of fire and forget manner then it might be fine.
legal? - it is legal - this code compiles and runs just fine
advisable? - not really, this is probably opinion-based but I would advise to use Executors together with Future and FutureTask
There are two reasons why I'd do this
Learning how to use anonymous threads
When I have a thread that has predictable behavior and I can guarantee completion within the thread.
I'd avoid this structure otherwise.
It is a bad way to do it because you need to copy/paste the run method for each Thread.
It is the same reason of why using method/class instead of put all code in one file.
buddy it totally depends on your requirement, there might be use cases where you need to access the private variables of the outer class hence you used inner anonymous class. And about the spawning new threads, say you are using it for a specific purpose say Network calls in that case you should use it properly where you design a thread pool and use a spawn a limited number of thread irrespective of number of network requests.
In my Java application with a Swing GUI, I would like to achieve the following.
There is a non-GUI thread running, performing some work. At one point, this thread needs input from the user before it can continue. Then, I would like to make some changes to the GUI, await a specific GUI action (like the user pressing the OK button), get the entered data from the GUI to the non-GUI thread, and let it continue with the computation.
Looking around, I have found a lot of information about how to initiate the execution of a (long running) task from the Swing GUI thread on another thread, but nothing on my problem.
SwingUtilites.invokeAndWait sounds like it does the job, but first, it takes a Runnable argument instead of a Callable, so there is no straightforward way to return a result, and second, it does not solve the problem of waiting for a certain GUI event.
I realize I could make up my own solution using e.g. a CountDownLatch, but to me, the problem seems frequent enough for there to be a standard solution.
So, my questions are: Is this really a frequent problem, and if yes, is there a solution in the standard library / libraries? If there is no standard solution, how would you solve it? If this problem doesn't occur often, why not?
Kicking off the GUI changes is easy, so I assume you're only asking about getting data back to the worker thread.
First, create a Blocking Queue. Have the worker thread call take() on the queue, and it will block. In GUI space, once the user enters valid input, put it on the queue with offer() and the worker thread will receive the data and can continue.
I think, you can use ExecutorService where you can also track progress of your task through Future interface.
java.awt.EventQueue.invokeLater works nicely for running code on the AWT EDT. Propbably best to copy mutable data or better use immutable data. Locks are possible, but a bit dicey.
If you other thread is an event dispatch loop, you could implement something like invokeLater for your thread (but don't make it static!). Probably use it behind some interface that makes sense to the behaviour of the thread - so it's real operations rather than run which is specified as doing anything it pleases. If your thread is going to block, then a BlockQueue is fine, but don't block from the AWT EDT.
java.awt.EventQueue.invokeAndWait is like using a lock. Probably you are going to use another lock. Or perhaps a lock like invokeAndWait on you own thread. If you don't, AWT uses a lock anyway. So, uncontrolled nested locks, that probably means deadlock. Don't use invokeAndWait!
final bool result = doSomething();
SwingUtilities.invokeLater( new Runnable(){
//Runnable method implementation.
//use result in your method like local var.
});
Make sure that your shared data is synchronized use lock objects.
If you need to pass arguments to Runnable just make your local variables final,
and use them in run method.
I just want to know what is the difference between the following two methods of invoking the thread.
Please look at the two pictures of the two scenarios
My problem is that the behavior i faced is when i follow "scenario 1" i lost control of my program and the
"// other commands" in MyClass didnt run
when i followed scenario two my sequence was smooth. has anyone noticed this behavior or is it a malfunction?
Kindly give your opinions.
Regards,
I guess that instead of implementing Thread (which is not an interface as already stated) you mean to implement Runnable.
So the question seems to be (it's just a guess, since your question is missing): who should start the thread - MyClass or MyThread?
Basically, I'd prefer scenario 1 since MyThread is actually just a runnable task and should not additionally handle the thread itself.
Thus MyClass should create and start the thread. This would additionally allow you to keep references to the spawned threads and maybe call join() or other methods on them later on.
As a sidenote, I'd change MyThread into this: public class MyRunnable implements Runnable { ... }
You might want to access the Thread object, e.g. to wait for it to finish or to poll it's state. In scenario 2 you might not do this because variable t is not accessible from the client code. In order to achieve this, you either had to make t visible from the outside code or override the Thread methods (which would be a bit futile). If invokeThread is meant as some sort of convenience method, you could consider returning t.
If scenario 2 is meant as "MyThread encapsulates running a thread and controls it's state", you don't have to extend Thread (which reads a bit confusing).
As mentioned in the other comment, I would second implementing Runnable rather than subclassing Thread for cleaner code.
I would like to know what are the differences between each of the following implementations for threads, and when should I use each option.
1- Implementing Runnable
public class ClientThread implements Runnable
{
new Thread(this).start();
public void run()
{...}
}
2- Extending Thread
class ServerThread extends Thread
{
this.start();
public void run()
{...}
}
3- Worker Threads and SwingWorker which I'm really not familiar with...
Thank you very much
Hi I've added another question in this matter below, it was published as an answer cause
I accidentally erased my cookies in the web browser thanks..
Okay guys thanks for all the info..
But, what should I use if I want to implement a count down timer for swing game which will run on screen parallel to the game without blocking the flow of the game because of the consistent timer in the background which will be shown there and probably will need to be run on the event dispatch thread...
Can I use the Runnable implementation or I must use swing worker?
This is the preferred way, since it separates the concerns of providing the code the thread should run (the job of the Runnable instance) and the job of managing the thread (the Thread instance), and also allows to have the Runnable be a subclass of something else
Less clean, but works just as well
"Worker Thread" is a conceptual name for threads that run parallel to the main application. SwingWorker is a class designed to implement a worker tread in a Swing application. It offers an API for the worker thread to communicate its status to the Swing event thread so that it can e.g. update a progress bar.
Note that it's generally very hard to work with threads manually. If you need multiple threads for performance reasons, it's much better to work with a thread pool via the Executors class.
In general, it's preferred to implement Runnable rather than extend thread. There are a few reasons for this. First of all, since Java doesn't support multiple inheritance, sometimes extending Thread isn't an option. Also, from an OOP perspective, it usually makes more sense to implement Runnable instead; you're not adding functionality to the Thread class, you're creating something to be run.
However, if you actually are adding functionality to Thread (in which case you will probably need to make lots of these Thread subclasses), then just extend Thread.
The official Java lesson on concurrency covers this very topic.
Defining and Starting a Thread
Which of these idioms should you use?
The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread.
The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread.
A very near duplicate from "implements Runnable" vs. "extends Thread" except the third point which I'm really not familiar with either. I would recommend reading that post as it contains a lot of very good info.
When you just want to run it in a separate thread. // The normal case
When extending the thread class functions or behavior.
Somebody else fill in :)
Almost all of the time you should use #1 due to it's semantics. You use it as a runnable you do not generally extend the thread class functions.
You should not use SwingWorker unless you are using swing.
Implementing Runnable (option 1) is generally preferable to extending Thread.
I tried to make a event dispatcher in Java that will dispatch events as threads. So all the EventListener classes are essentially implemented the Runnable class. Like how firing of events work traditionally, a method in the event dispatcher class loops through a list of EventListeners and then invoke their handler method, except that this time, I invoke these handler as threads by putting the listeners into new Thread(handlerObject).start(). The actual handling is done in the run() method in the EventListener.
So it looks something like:
for(EventListener listener : listenerList) {
if(listener instanceof Runnable)
new Thread(listener).start();
}
So all instructions to handle the event in the listener are put inside the run() method, which will be executed when the thread.start().
But the problem is the threads often go into a situation where one of the threads got stuck somewhere and didn't manage to continue. Sometimes, several threads may also get stuck while some managed to run through all instructions in the run() method in the listener. I looked up and this sounds like what it is called a deadlock.
I tried to put the "synchronized" modifier to all my methods but it still has this problem. I thought the synchronized keyword would simply just queue any threads trying to run a similar method until a current thread running the method has finished. But this doesn't solve the problem still. Why doesn't synchronized solve the problem especially when I already have it on all my methods and it should queue any concurrent access that may potentially cause a deadlock? I didn't use any wait() or notify() methods. Just a simple event dispatcher that attempts to run its event listener as a thread.
I am pretty new to threads but have found it very difficult to even debug it because I don't know where has gone wrong.
Thanks for any help.
Deadlock is something along the lines of this:
A needs iron to make tools, asks B for
iron
B needs tools to make iron,
asks A for tools
Neither will complete. Just because you've put the syncronized key word around them does not guarantee that you're going to run into a logical impossibility. You have to judge when one thing will be able to move forward and when it won't.
Never just add synchronized to all methods, this solves nothing - you will effectively make your program single-threaded.
When you think you have a deadlock, you can take a thread dump and analyze the output to understand what each thread is executing, which locks (if any) they are holding, what locks they are waiting for, etc.
Unfortunately without specific code or understanding the actual synchronization going on in your application, the only advice that can be given is general like this.
I don't know what you mean by 'deadlock despite synchronized keyword'. The `synchronized' keyword doesn't prevent deadlocks. It can cause them, if you have two threads that acquire locks in different orders. Solution: don't.
Your real problem is that you don't understand concurrency well enough to understand why your program is not working, let alone how to solve this. (FWIW - adding synchronized to all of your methods is only making the problem worse.)
I think that your best plan is take time out to do some reading on concurrency in Java. Here are a couple of good references:
The Java Concurrency Tutorial Stream.
Java Concurrency in Practice by Brian Goetz et al.
#wheaties has a micro-explanation of what a deadlock is, and #matt_b offers useful advice on how to diagnose a deadlock. However, these won't help a lot unless you know the right way to design and write your multi-threaded code.