android runnable difference - java

What is the different b/w running runnable inside handler new Handler().post(runnable) and running in Thread(runable) ?

Handler is used for communication between and coordinating threads. By creating a Handler, you bind it to the current thread. If you post a runnable to that Handler, it will be executed in that same thread.
Thread is Java's way to spawn new user-level threads. The runnable you pass it will be executed in that thread.
The two concepts are not mutually exclusive. You can use Handler with custom Threads.

Related

Handler and interface runnable - which have new thread

I have read on stack this:
When you use new Handler().post(r) (or Message), you added the
Runnable object to Looper and execute the code later in the same
thread.
this answer is accepted.
So now I have a dilemma, some guys on my last interview give me tip: if you want to run something in other thread and update from this new thread UI, lets use a Handler.
So Handler is new thread or not ?
Or maybe runnable in this thread works on other thread ?
Can somebody explain me ?
from official doc:
There are two main uses for a Handler: (1) to schedule messages and
runnables to be executed at some point in the future; and (2) to
enqueue an action to be performed on a different thread than your own.
Handler is not a new thread. It is just a mechanism to schedule some task to be done in the UI thread.
Creating/Posting to a Handler does not create new thread.
The Runnable posted to a Handler runs in the UI thread as soon as UI thread becomes free.
When you create a Runnable instance and post it, its reference gets stored and its run method will be called from the UI thread, at some point in the future. (You can also specify the delay using the method postDelayed().)
A Handler is associated with a Looper (and that Looper's thread). When you call new Handler() to create a new handler you're associating it with the Looper for the current thread (the thread where the current code is running).
Once you have this object, you can use it from another thread to report results, etc.
So for example, from a background thread you can call post() on a handler object that is associated with the UI thread. The Runnable you pass will be executed by that handler in its thread (not in the thread where the post() function was called) when the Handler gets to it.
For another source of info/details on loopers and handlers see https://developer.android.com/training/multiple-threads/communicate-ui
Here's the quote form Android documentation:
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
This part is quite important:
When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it
Handler is not a new thread and it can handle messages in a queue when you're passing new Runnables to the Looper thread, which process them. Each message can be processed in a separate thread or thread pool, when you explicitly do it. Otherwise, it will be processed in the thread, where Looper was created (it can be main/UI thread or other thread).
I was also confused about this mechanism some time ago, collected some links, resources and wrote sample app using Handler and Looper. You can check it here: https://github.com/pwittchen/android-looper-sample. Maybe you'll find it useful.

How to post callbacks in Android to any arbitrary thread

I am using the Unity game engine which also supports exporting to Android.
The engine uses multiple threads, including the UI thread and a separate scripting thread where all the user custom code is executing.
My scenario requires that i call some operation in a background thread, and i would like to marshal the result back to the main scripting thread.
I know the basics of the AsyncTask, Executor and Looper classes. Out of these, Looper seems like a good candidate since it allows setting up a queue and post back messages to a given thread (AsyncTask is "hardwired" to run the callback on the UI thread, which is not what i want here).
What is the proper way of achieving this?
There is 3 main ways to communicate with the UI thread :
Activity.runOnUiThread(Runnable)
View.post(Runnable)
Handlers
In your case, I advice you to create an Handler, as the 2 first solutions imply that you have a reference on your Activity or a View
Edit
If you want to use any thread in your app, just make sure a Looper has been set, and use an associated Handler
class YourLooperThread extends Thread
{
// make it accessible from the outside
private Handler handler;
#Override public void run()
{
Looper.prepare();
// Customize your handler, it has to be used in any thread which want to push a message in this thread's looper message Queue
handler = new Handler();
Looper.loop();
}
}
Be careful : all the other tasks you want to do in that thread must be done through the message queue, i.e posting a runnable in the handler. More information here : Handlers, MessageQueue, Looper, do they all run on the UI thread?

Callable Threads versus Runnable Threads versus Extend Thread

I was recently reading about creation of Threads in java by implementing Runnable or Extending thread and last Implementing Callable. Runnable Versus Callable thread at stackoverflow describes the difference quoting both are designed for classes whose instances are potentially executed by another thread. What does it mean? Does it creates new Thread? If yes, why we need to pass a class that implements Runnable to Thread constructor?
Also, i saw the method of creating threads by implementing Runnable or Extending thread. In the first method, (in the tutorials what i found), we need to call Thread class which requires the Runnable instance to start the thread. But, i could not found the similar thing for Callable as there is no Thread constructor which accepts Callable. Executor framework or Future Task is used for the purpose of running those threads. Then why we say both ways are same (except Callable retruns something and can throw Exception).
Last, is writing
Thread t = new Thread();
Thread t1 = new Thread(new RunnableInstance());
Do these create new Threads in system? Is there any other way of using Runnable to create new threads without passing it as a constructor to Thread class?
It should not be a duplicate question.
What does it mean? Does it creates new Thread?
Both Callable and Runnable are just interfaces, they don't create any threads by themself. Instead they provide API and abstractions for developers. When you want to execute some code in separate thread you typically implement Runnable and then you can decide how to execute this. It is not bound to any thread yet. You have many options actually:
Execute it in the new Thread
Execute it with some ExecutorService
Or just call it directly
If yes, why we need to pass a class that implements Runnable to Thread constructor?
No.
Since Runnable does not create thread behind (well, it simply can't since it's just an interface!), we need to execute this Runnable explicitly.
Do these create new Threads in system?
Yes.
Is there any other way of using Runnable to create new threads without passing it as a constructor to Thread class?
Yes. I mentioned already ExecutorService. You can profit from thread pool or completion service, take a look at the API and examples.
Callable
It will return the result of the execute.
Runnable
It wont return. But it will run separately like callable.
Extends Thread
Its also a runnable. But if you extend thread , you cant extend any class since java wont support multiple inheritance.
Callable and Runnable provides interfaces for other classes to execute them in threads. They contain no functionality of their own. The most common way to do this is via an ExecutorService. Have a look at the classes available in java.until.concurrent. There are many options there. Extending Thread is not really called for unless you really intend to add new low-level threading functionality.

What is a Runnable (Java) counterpart in Objective-C?

What is a good way to schedule tasks on the Main thread in Objective-C? Does any of the following ways create a new thread?
performSelector afterDelay
dispatch_after
Neither creates a new thread. the two just schedule a call on the current NSRunLoop.
GCD uses an internal thread pool and dispatch_async schedules a call on any of these threads. That is one 'counterpart' for a Runnable (when used with a Thread object / a Threadpool).
Another 'legacy' way is NSThread's detachNewThreadWithSelector or performSelectorInBackground! :)

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).

Categories

Resources