Does each class have its own Thread by default? - java

I'm working with a GUI and I'm using
Thread.sleep();
in some of the classes, and I'm wondering if I need to create a separate Thread for my Main class (the GUI class), or if each class has a separate Thread by default. Note, the reason that I bring up Thread.sleep(); in the first place is that when working with GUI's Thread.sleep(); pretty much freezes your GUI. Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.

Thread.sleep() is a static method of Thread class. Hence, whichever class you place in a method, during runtime, if a thread call flow encounters this class method where Thread.sleep() in invoked, the thread will be blocked for that amount of time.
Your Question:
Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.
each class has a separate Thread by default -- INCORRECT Statement
-- Thread class is not inherited by every class
-- In normal sense, Thread is a call flow. It executes whichever class it encounters thru its method calls.
-- Class and Thread are 2 separate concepts.
---- Class is a definition of an entity,it cannot run by itself, it can be loaded, instantiated with data, method calls can be done and garbage collected.
---- Thread is an execution entity at run-time.It can be started, runnable, blocked, stopped. To support this concept, Java has provided Thread class or Runnable interface to extend/implement respectively.
do I need to create a separate Thread for my Main class?
-- your mainclass will be executed in a MainThread which is instantiated and started by your JVM.
-- It is better to define a seperate user-defined Thread to start your GUI.
-- If either in the MainThread (or) user-defined Thread, if it encounters Thread.sleep() during call flow, that particular thread will be blocked.
One more thing, your question is not clear on your need for usage of Thread.sleep(). You just have given a reason of the resultant usage of it but not the need for usage.

From javadoc for Thread:
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds, subject to the
precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors.
Don't mind that the sleep() method is static, it is executed for the thread in which you call it. So if you call it from GUI, it puts your main UI thread into sleep, hence freezing UI completely.

by default the program does not have more than one thread. there should be only one class which has a main method. it does not matter it is a ui application or any other type of application.
please post the details in what scenario you want to use the sleep function.

When a java class is created automatically 3 thread are created by-default with it.
1.Main Thread
2.Thread Scheduler
3.Garbage Collector thread

Please watch this explanatory video to understand what a Thread actually is.
In this example the Thread is the music box, your code is the sheet of paper, and the processing time granted to a thread is the rotation of the handle.
So your main-class code (sheet-of-paper) is inserted into a thread (music-box) generated by the JVM and execution is started (handle rotates). Once you call sleep(1000) "rotations of the handle" is paused for 1 second, and so is the execution of your code. Thread.sleep() is just a short-cut to Thread.getCurrentThread().sleep().
If you now have several threads (music-boxes), you can of course pause one while another still runs. So if you have a main thread and a GUI thread, you can pause the main thread and your GUI will work fine (unless it actually tries to access the main thread). If you however pause the GUI thread, it will appear to be frozen.

Related

How to implement Asynchronous Inter Thread Communication in java?

I am developing one code in which I have one parent thread and one child thread.Now, my scenario is like mentioned below,
Parent thread start the child thread
after starting the child thread it continuous to work what it is doing.
Now one time occurs that child thread want to call the method in the main thread
then it call asynchronously the main thread with that method.
I also want to clarify that I know the concurrency package in java but it is doing synchronously i.e. main thread have to wait for the child thread till it complete the execution,but I want the main thread to do continuous work while child thread executing.
My implementation is like SwingWorker Thread in java
You don't get to "call a method in the main thread". The only thing you can do is implement a specific mechanism whereby the main thread, by its own initiative, executes a method on an object which was provided by the child thread.
The above roughly describes what the Swing's mechanism does: the "main" thread (in that case, the Event Dispatch Thread) dequeues objects from a global queue and, if the object's type is appropriate, invokes the run method on an associated instance of Runnable.
Main point: in Swing the EDT doesn't "continue to work what it is doing"; it specifically waits for other threads to tell it what to do via this mechanism and otherwise just blocks, doing nothing at all.

Dispatch a task from EDT to main?

I've been reading a bit about concurrency (which gives me a headache).
I understand you can set a task to run on the EDT from the main thread using:
SwingUtilities.invokeLater
but can you set a task to run on the main thread from the EDT?
As in:
Thread mymainthread=Thread.currentThread();//<referring to the thread that initially kicks off public static void main
public void mousePressed(MouseEvent e){ //queue a task to run on mymainthread }
Can it be done? Is it a bad idea?
The other question on SO similiar to this (here) talks about creating a new thread but wouldn't it be safer and simpler to keep using the main if I was aiming for a single thread (+EDT) application? .......or maybe I've got this all wrong.
EDIT: What I should have explained: I wanted to create objects that would communicate with each other on the main thread (running in a slow loop) so I didn't want any of them be instantiated on a different thread, edt or otherwise.
but can you set a task to run on the main thread from the EDT?
I think you are confused on what EDT is. Swing and many other frameworks use a technique called thread-confinement.
In order to guarantee thread-safety, all actions are executed from a single thread. This thread in Swing is called Event Dispatcher Thread.
This thread has a queue and executes all tasks from that queue sequentially one at a time, at the same thread. This is why your tasks should be short in order not to block the UI.
So when you use EDT you are essentially passing a task to its queue from your thread and EDT will eventually execute it.
What you can do is put a task on the EDT queue which spawns a thread to be executed on separate thread. If you want to use your current thread for some reason as the background thread perhaps you could but why would you need that? The most straightforward way is just to submit a runnable to run as part of some background thread e.g. part of a pool
You can create your own event loop to do thread-confinement. This would allow you a separate single thread which would behave like the EDT. Be careful not to share [effectively] mutable objects between the two threads simultaneously.
Implementation can be as simple as a while loop with a BlockingQueue. You can go slightly higher level by getting an ExecutorService from java.util.concurrent.Executors.newFixeThreadPool(1).

Java - Run a runnable on an existing thread?

I am trying to switch back to an existing thread from a spawned child interface callback. Does anyone know how? The callback implementation always runs from the child thread where where it was called, not the implementing class...
What do you mean switch back?
Cause a context switch that will return you to "original" thread that spawned the child thread?
If so, this is not possible. It contradicts Multi-threading concepts.
If you want to have some work done on the "original" thread, while the "child" thread is running,
You can consider having a queue between the child and the original thread (i.e - Producer/Consumer).
The child thread will put a "job" on the queue, and the "original" thread will consume it.
However,the "original" thread will have to block on the the "child" thread.
Another way to implement this is using wait and notify, (child thread will notify) - but once again, original thread will have to wait.
Last approach will be to simply wait on the child thread execution to end, if you want to return to the original thread at the end of execution of child thread.
The question is - is waiting at the original thread is acceptable at your scenario?
You simply have the calling thread wait() on an object, and have the child thread notify() the same object.
When wait() is called, the calling thread will halt.
When notify() is called, the waiting thread will wake up and continue on.
These calls must be made within a synchronized block/method.
Swing uses the concept of an Event Dispatch Loop (EDL), and all Swing component interaction must run on the the EDL's thread. This sounds analogous to what you want to do, and to what zaske proposed in his response.
You might find the following helpful in formulating your solution:
SwingUtilities, in particulare it's invokeLater(Runnable) method.
SwingWorker if you want to get fancy and start even more threads.
Since this is also tagged java-ee I'll mention that you are not allowed to start threads in any Java EE app server. It introduces several issues:
Easy to bleed the server of thread resources
Can prevent undeployment of the application
Can prevent server shutdown if threads are not marked as daemons
Loss of functionality such as JNDI, Transactions, Security
It's generally a no-no. You might instead look into the #Asynchronous annotation which allows you to easily do fork/join kinds of logic safely with the cooperation of the container.
This answer has a very complete explanation of how #Asynchronous methods work including example code https://stackoverflow.com/a/6158773/190816

Java Thread to manage socket and run class method

I have a Java thread that I start so it keeps listening to a socket (considering the a socket read is blocking a thread is needed).
After the Thread receives the data from the socket it needs to call a method from a class.
Now I have two options to do this:
Declare an interface that is passed to the Thread and implemented in a class. When the thread calls the interface method the implementing classes will run it.
Or I can pass the class instance to the Thread as a parameter and then call the class method.
But I wanted to know if the thread blocks while the method is running.
I suppose so but I'm not sure.
I wanted the thread to have a Socket event behavior. What I mean is to only be responsible for reading the data from the socket and fire functions in the main Class, the one that called the Thread.
Yes, the thread will block while executing the method, so it can not read from the socket at the same time. No information will be lost, the transfer only takes longer and you can get a socket timeout if the computation takes too long.
If your method takes much time to run, you should execute it in another worker thread. I recommend to use an Executor for that.
You have various options :
Make your class a child class of Thread (easier code but you'll merge functionnal part - your main code - with a technical aspect (extending the Thread))
Make your class implements the Runnable interface and start a new thread with that Runnable (i often do like that). So your main code still remains in a overriden run method, but the inheritance tree is up to you (your main class can extend one of your other class)
Keep separated your main code / the thread with two classes (one for your main code, one for the thread), linking the two at your will (remember that if you make an inner thread inside another class, the inner thread can use any final properties, for example).
As stated in other answers, anything happening in your run() method is of course blocking the execution.
As a sidenote, if you're going to deal with threads and sockets, i strongly suggest you to have a look at NIO frameworks like Netty that are just there for this kind of behavior : event driven client/server application through NewIO sockets.
As another sidenote, i often use this pattern :
start an acquisition thread that will catch the event ;
push them in a linkedblockingqueue (queue.offer()) ;
have another thread that shares the same linkedblockingqueue (with queue.take()) : this operation is blocking, the threads will be blocked as long as the queue is empty ;
This is a very simple way to have one thread as "producer", and one thread as "consumer". You can even have various consumers awaiting on the same queue.
But I wanted to know if the thread blocks while the method is running
Yes it does block.
If inside run you call a method to process something it doesn't matter if that is an interface etc as you ask it only matters what does the method actually do
In your case you have only 1 option.
Make sure that you return the control back to your socket listening thread asap.
This can happen by designing/mandating the processing class to handle the processing in a different thread.
Actually your problem is not something new. In event based designs there is the requirement to process the event as fast as possible so as to not block the event queue based flow.
And this is how I would recommend you to design arround. Not use any interface to interact with the listening thread but register an event listener(s).
When an event occurs i.e. your listening thread reads data, it will pass the data as event to your listener(s) at which point of course it will block.
Then you should start a new thread to do the processing and the listening thread can continue with its work

Java GUI, need to pause a method without freezing GUI aswell

I know that this problem is caused by the sleep or wait calling on the main thread and that the answer on how to solve this will be to put the method into a seperate thread and then make that thread sleep. But the code is a mess and don't really have the time to sort it out and split it up into separate threads and was wondering if there is any other way of doing this? Even if it is not the cleanest or most common practice for working with GUIs. I only need about a seconds pause from the method.
You can't do it without creating a separate thread. Creating a thread in Java is easy. The only thing to pay attention to is that you can only touch the UI through the main thread. For this reason you need to use something like SwingUtilities.invokeLater().
It is not possible to sleep on an event thread and not cause a GUI freeze. However in Swing, the event thread is created and managed behind the scenes - you main thread (the one originating from main() method) is not the event thread.
So, you can safely sleep on your main thread.
Using a separate thread for the code is your only solution. Every action started by the Swing thread must be delegated to a separate thread if it would otherwise block the GUI.
I wrote a super simple delay function for java that doesn't let your GUI freeze . It has worked everytime i have used it and i guess it will work for you too.
void Delay(Long ms){
Long dietime = System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<dietime){
//do nothing
}
}
For eg : To delay a thread by 5 millisecods use Delay(5L)
And where would one declare this thread. Please bear in mind any, any reference to a function that contains thread sleep will cause the main thread to pause. Because the main thread will have to wait the the sub thread to pause.
The reality is that threads don't realy work as seperate independant thread because a thread must be started from another thread. In other words if you are creating desktop application, and even if you don't work with other threads, your application is a one threaded application. Now if you start working with threads & putting them to sleep, you will soon find out that that you won't be able to do anything else in the application. No & no the other threads won't even run because they are waiting the first thread to finish sleeping. Why is this? Cause the thread are sub threads of the main thread and it is the main thread that is waiting for that sleep sub thread to wake up. You can't design a threadless application either as java is single main threaded application. Any, yes any, thread further defined in your application always runs inside in the main thread.
Unless somebody can prove me wrong, you obviously whould never pause your main thread as this would lock up your app. However as soon you define another thread and suspend it with sleep() this also locks up your app as the thread was defined in subclass of the main application and therefore the main thread.
So to put a very very long story to bed, pausing a user defined thread, is almost exactly the same as if your called the Thread.sleep() for anywhere in your app, it
pauses the entire application.

Categories

Resources