Java run main method in thread main

Running code in main thread from another thread

In an android service I have created thread(s) for doing some background task. I have a situation where a thread needs to post certain task on main thread’s message queue, for example a Runnable . Is there a way to get Handler of the main thread and post Message / Runnable to it from my other thread?

You can also use Custom broadcast receiver. try my answer here, [Inner Broadcast Receiver][1] [1]: stackoverflow.com/a/22541324/1881527

There are many ways. Apart from David’s answer & dzeikei’s comment in his answer, (3) you can use a Broadcast Receiver, or (4) pass the handler in extras of Intent used to start the service, and then retrieve the main thread’s handler inside service using getIntent().getExtras() .

@sazzad-hissain-khan, Why tag this question from 2012 with mostly answers in Java with the kotlin tag?

16 Answers 16

NOTE: This answer has gotten so much attention, that I need to update it. Since the original answer was posted, the comment from @dzeikei has gotten almost as much attention as the original answer. So here are 2 possible solutions:

1. If your background thread has a reference to a Context object:

Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:

// Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(context.getMainLooper()); Runnable myRunnable = new Runnable() < @Override public void run() // This is your code >; mainHandler.post(myRunnable); 

2. If your background thread does not have (or need) a Context object

// Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(Looper.getMainLooper()); Runnable myRunnable = new Runnable() < @Override public void run() // This is your code >; mainHandler.post(myRunnable); 

Thanks David it worked out for me, one more thing if you could help me with, if I extend Handler and impl handleMessage() would it prevent main thread from handling its messages ? that’s only a question out of curosity..

No. If you subclass Handler (or use Handler.Callback interface) your handleMessage() method will ONLY be called for messages that have been posted using your handler. The main thread is using a different handler to post/process messages so there is no conflict.

I believe you won’t even need context if you use Handler mainHandler = new Handler(Looper.getMainLooper());

@SagarDevanga This is not the right place to ask a different question. Please post a new question , not a comment to an unrelated answer. You will get better and faster response that way.

As a commenter below pointed correctly, this is not a general solution for services, only for threads launched from your activity (a service can be such a thread, but not all of those are). On the complicated topic of service-activity communication please read the whole Services section of the official doc — it is complex, so it would pay to understand the basics: http://developer.android.com/guide/components/services.html#Notifications

The method below may work in the simplest cases:

If I understand you correctly you need some code to be executed in the GUI thread of the application (cannot think about anything else called «main» thread). For this there is a method on Activity :

someActivity.runOnUiThread(new Runnable() < @Override public void run() < //Your code to run in GUI thread here >//public void run() < >); 

Hope this is what you are looking for.

OP says he is running threads in a Service . You cannot use runOnUiThread() in a Service . This answer is misleading and doesn’t address the asked question.

Kotlin versions

When you are on an activity, then use

When you have activity context, mContext then use

When you are in somewhere outside activity where no context available, then use

Handler(Looper.getMainLooper()).post < //code that runs in main >

There is another simple way, if you don’t have an access to the Context.

1). Create a handler from the main looper:

Handler uiHandler = new Handler(Looper.getMainLooper()); 

2). Implement a Runnable interface:

Runnable runnable = new Runnable() < // your code here >

3). Post your Runnable to the uiHandler:

That’s all 😉 Have fun with threads, but don’t forget to synchronize them.

A condensed code block is as follows:

 new Handler(Looper.getMainLooper()).post(new Runnable() < @Override public void run() < // things to do on the main thread >>); 

This does not involve passing down the Activity reference or the Application reference.

 Handler(Looper.getMainLooper()).post(Runnable < // things to do on the main thread >) 

If you run code in a thread, e.g. do delaying some action, then you need to invoke runOnUiThread from the context. For example, if your code is inside MainActivity class then use this:

MainActivity.this.runOnUiThread(new Runnable() < @Override public void run() < myAction(); >>); 

If your method can be invoked either from main (UI thread) or from other threads you need a check like:

public void myMethod() < if( Looper.myLooper() == Looper.getMainLooper() ) < myAction(); >else

@DavidWasser Is that documented anywhere? The method docs don’t mention anything about it. developer.android.com/reference/android/app/…

@GregBrown As you’ve indicated by your link to the Activity documentation, runOnUiThread() is a method of Activity . It is not a method of Service , therefore you cannot use it. What could be clearer than that?

@DavidWasser Fair enough. I don’t even remember why I asked that question now (it was posted almost a year ago).

I know this is an old question, but I came across a main thread one-liner that I use in both Kotlin and Java. This may not be the best solution for a service, but for calling something that will change the UI inside of a fragment this is extremely simple and obvious.

HandlerThread is better option to normal java Threads in Android .

  1. Create a HandlerThread and start it
  2. Create a Handler with Looper from HandlerThread : requestHandler
  3. post a Runnable task on requestHandler

Communication with UI Thread from HandlerThread

  1. Create a Handler with Looper for main thread : responseHandler and override handleMessage method
  2. Inside Runnable task of other Thread ( HandlerThread in this case), call sendMessage on responseHandler
  3. This sendMessage result invocation of handleMessage in responseHandler .
  4. Get attributes from the Message and process it, update UI

Example: Update TextView with data received from a web service. Since web service should be invoked on non-UI thread, created HandlerThread for Network Operation. Once you get the content from the web service, send message to your main thread (UI Thread) handler and that Handler will handle the message and update UI.

HandlerThread handlerThread = new HandlerThread("NetworkOperation"); handlerThread.start(); Handler requestHandler = new Handler(handlerThread.getLooper()); final Handler responseHandler = new Handler(Looper.getMainLooper()) < @Override public void handleMessage(Message msg) < txtView.setText((String) msg.obj); >>; Runnable myRunnable = new Runnable() < @Override public void run() < try < Log.d("Runnable", "Before IO call"); URL page = new URL("http://www.your_web_site.com/fetchData.jsp"); StringBuffer text = new StringBuffer(); HttpURLConnection conn = (HttpURLConnection) page.openConnection(); conn.connect(); InputStreamReader in = new InputStreamReader((InputStream) conn.getContent()); BufferedReader buff = new BufferedReader(in); String line; while ((line = buff.readLine()) != null) < text.append(line + "\n"); >Log.d("Runnable", "After IO call:"+ text.toString()); Message msg = new Message(); msg.obj = text.toString(); responseHandler.sendMessage(msg); > catch (Exception err) < err.printStackTrace(); >> >; requestHandler.post(myRunnable); 

Источник

Running code on the main thread from a secondary thread?

This is a general Java question and not an Android one first off! I’d like to know how to run code on the main thread, from the context of a secondary thread. For example:

new Thread(new Runnable() < public void run() < //work out pi to 1,000 DP (takes a while!) //print the result on the main thread >>).start(); 

That sort of thing — I realise my example is a little poor since in Java you don’t need to be in the main thread to print something out, and that Swing has an event queue also — but the generic situation where you might need to run say a Runnable on the main thread while in the context of a background thread. EDIT: For comparison — here’s how I’d do it in Objective-C:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0UL), ^< //do background thread stuff dispatch_async(dispatch_get_main_queue(), ^< //update UI >); >); 

6 Answers 6

There is no universal way to just send some code to another running thread and say «Hey, you, do this.» You would need to put the main thread into a state where it has a mechanism for receiving work and is waiting for work to do.

Here’s a simple example of setting up the main thread to wait to receive work from other threads and run it as it arrives. Obviously you would want to add a way to actually end the program and so forth.

public static final BlockingQueue queue = new LinkedBlockingQueue(); public static void main(String[] args) throws Exception < new Thread(new Runnable()< @Override public void run() < final int result; result = 2+3; queue.add(new Runnable()< @Override public void run() < System.out.println(result); >>); > >).start(); while(true) < queue.take().run(); >> 

Ah okay, so in practice I guess this sort of defeats the purpose of using a background thread since the main thread is blocked waiting for the background thread. That said, it does look like a pretty neat mechanism! I’ll read up more about queues now!

You could certainly have the main thread doing some other work and just check on the queue at intervals rather than do nothing but block on it. But at some point it stops being worth home-brewing things Swing provides perfectly good tools for 🙂

Actually, that’s quite a good idea for what I’m doing — I’m not using Swing as the project is actually a simple game written using the Slick2d engine (otherwise you’re right; I would just use Swing’s built-in tools for it!)

What do you think the actual implementation of the «pretty» iOS APIs looks like under the hood? 🙂 There are pretty APIs for java/android too, but the original question specifically asked how it actually works without using the library tools.

@János we have looper and handler in Android that you can post a runnable to the ui thread using them. this is pure java and what the looper and handler is doing under the hood.

In case you are on Android, using a Handler should do the job?

new Handler(Looper.getMainLooper()).post(new Runnable () < @Override public void run () < . >>); 

I know there is a method called runOnUIThread() but not in every circumstance the code is written in Activity . This answer saved me a lot of time. Thanks!

Yes but he has extended the previous answer. This allows others with the same question, like me, to be given a clear description about different platforms running java

An old discussion, but if it is a matter of sending request to the main thread (an not the opposite direction) you can also do it with futures. The basic aim is to execute something in background and, when it is finished, to get the result:

public static void main(String[] args) throws InterruptedException, ExecutionException < // create the task to execute System.out.println("Main: Run thread"); FutureTasktask = new FutureTask( new Callable() < @Override public Integer call() throws Exception < // indicate the beginning of the thread System.out.println("Thread: Start"); // decide a timeout between 1 and 5s int timeout = 1000 + new Random().nextInt(4000); // wait the timeout Thread.sleep(timeout); // indicate the end of the thread System.out.println("Thread: Stop after " + timeout + "ms"); // return the result of the background execution return timeout; >>); new Thread(task).start(); // here the thread is running in background // during this time we do something else System.out.println("Main: Start to work on other things. "); Thread.sleep(2000); System.out.println("Main: I have done plenty of stuff, but now I need the result of my function!"); // wait for the thread to finish if necessary and retrieve the result. Integer result = task.get(); // now we can go ahead and use the result System.out.println("Main: Thread has returned " + result); // you can also check task.isDone() before to call task.get() to know // if it is finished and do somethings else if it is not the case. > 

If your intention is to do several stuff in background and retrieve the results, you can set some queues as said above or you can split the process in several futures (starting all at once or starting a new one when needed, even from another future). If you store each task in a map or a list, initialized in the main thread, you can check the futures that you want at anytime and get their results when they are done.

Источник

Execute main thread method in child thread

I have a class called Test Example and it has one method called dance(). In the main thread, if I call the dance() method inside the child thread, what happens? I mean, will that method execute in the child thread or the main thread?

public class TestExample < public static void main(String[] args) < final TestExample test = new TestExample(); new Thread(new Runnable() < @Override public void run() < System.out.println("Hi Child Thread"); test.dance(); >>).start(); > public void dance() < System.out.println("Hi Main thraed"); >> 

Try putting System.out.format(«thread: %s\n», Thread.currentThread().getName()); inside main and run . You will have your answer.

2 Answers 2

1. The method dance belongs to the Class TestExample, NOT to the Main thread.

2. Whenever a java application is started then JVM creates a Main Thread, and places the main() methods in the bottom of the stack, making it the entry point, but if you are creating another thread and calling a method, then it runs inside that newly created thread.

3. Its the Child thread that will execute the dance() method.

See this below example, where i have used Thread.currentThread().getName()

 public class TestExample < public static void main(String[] args) < final TestExample test = new TestExample(); Thread t = new Thread(new Runnable() < @Override public void run() < System.out.println(Thread.currentThread().getName()); test.dance(); >>); t.setName("Child Thread"); t.start(); > public void dance() < System.out.println(Thread.currentThread().getName()); >> 

Источник

Читайте также:  Html style position bottom right
Оцените статью