'Access vs execute thread's method [duplicate]
Does this line:
ClientThread.ClientSocket.getInputStream().read()
takes ClientThread's method and executes it on MainUI thread, or does it tell ClientThread to execute it?
It results in MainThreadNetworking Exception so I believe it's the first option, sadly. If so, how can I execute that method in the ClientThread instead?
Solution 1:[1]
There is no way to tell another thread to execute something. So, no, the above simply runs it in your thread. Note, there's the concept 'Thread -a thing that runs on an OS core' and 'java.lang.Thread - an object that represents that concept'. They are not quite identical. I'll use j.l.Thread to indicate the Thread object and just thread for the OS concept. j.l.Thread is just an object, it's not particularly magical. Just interacting with a j.l.Thread instance is just.. interacting with an object. It doesn't convey magical 'anything you do with this object somehow runs in a separate thread' powers.
There are only only 2 ways to tell another thread (OS-level or j.l.Thread) to execute something, i.e., only 2 ways to use j.l.Thread to actually run stuff in separate threads:
- When creating a
j.l.Thread, you pass along the 'run()' code (either passing a Runnable, or extending Thread and supplying arun()method). When some thread runs the codethatThreadObject.start()(note: not run!) - then that starts an actual thread, and that newly created thread will, after initializing, begin by executing the code in that run() method of thej.l.Threadobject. - By programming it. In other words, perhaps some thread looks like this:
private class Runner extends Thread {
private final ArrayBlockingQueue <Runnable> queue = new ArrayBlockingQueue<>(1000);
public void offer(Runnable r) {
queue.add(r);
}
@Override public void run() {
while (true) {
Runnable r = queue.take();
r.run();
}
}
}
Then, imagine some code is running in a thread (not the thread represented by the j.l.Thread instance made from the above code), and calls thatThreadObj.offer(() -> System.out.println("Hello!");...
then eventually the thread represented by that j.l.Thread will run it. Because you programmed it to do this.
If you want something like that, note that the java.util.concurrent package has implementations of this concept (ExecutorPool and friends). Don't write it yourself.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rzwitserloot |
