How to Call a Method with a Separate Thread in Java

How to call a method with a separate thread in Java?

Create a class that implements the Runnable interface. Put the code you want to run in the run() method - that's the method that you must write to comply to the Runnable interface. In your "main" thread, create a new Thread class, passing the constructor an instance of your Runnable, then call start() on it. start tells the JVM to do the magic to create a new thread, and then call your run method in that new thread.

public class MyRunnable implements Runnable {

private int var;

public MyRunnable(int var) {
this.var = var;
}

public void run() {
// code in the other thread, can reference "var" variable
}
}

public class MainThreadClass {
public static void main(String args[]) {
MyRunnable myRunnable = new MyRunnable(10);
Thread t = new Thread(myRunnable)
t.start();
}
}

Take a look at Java's concurrency tutorial to get started.

If your method is going to be called frequently, then it may not be worth creating a new thread each time, as this is an expensive operation. It would probably be best to use a thread pool of some sort. Have a look at Future, Callable, Executor classes in the java.util.concurrent package.

Easy way to call method in new thread

Firstly, I would recommend looking at the Java Thread Documentation.

With a Thread, you can pass in an interface type called a Runnable. The documentation can be found here. A runnable is an object that has a run method. When you start a thread, it will call whatever code is in the run method of this runnable object. For example:

Thread t = new Thread(new Runnable() {
@Override
public void run() {
// Insert some method call here.
}
});

Now, what this means is when you call t.start(), it will run whatever code you need it to without lagging the main thread. This is called an Asynchronous method call, which means that it runs in parallel to any other thread you have open, like your main thread. :)

Calling a method in a running thread, from outside the thread

It doesn't work like this: threads don't own methods. A thread is nothing but a "sequence of activity".

Calling a method on a thread object will run that method within the same thread that is running the client code which invokes that method.

You should do that differently: one typically approach is that the other thread keeps polling the content of some shared data structure. Normally you would use some sort of queue for that.

Thread A puts some kind of command into a queue and thread B reacts to that at some point.

But please note: such designs are somehow "last decade". Nowadays you rather avoid using bare threads and low level interactions between them. Instead you look into advanced abstractions - such as ExecutorService, Futures,...

What happens when you call a method in a thread that is already working?

All methods called are using the current thread for all objects. If you call a method on Thread it also calls that method like any other on the current thread.

The only one which is slightly confusion is that start() starts another thread and calls run() for that new thread.

This is one of the reasons it is best not to extend Thread but pass a Runnable to it as too often the methods either don't do what they appear to or you get side effects you don't expect.

NOTE: Java often has a proxy object on the heap for managing a resources which is actually off heap (native). E.g. direct ByteBuffer or JTable or Socket or FileOutputStream. These objects are not the actual resource as the OS understands them, but an object Java uses to make it easier to manage/manipulate the resource from Java code.

how to call a method with multiple threads

if you need simultaneous execution and each time new thread you can find the solution here

public class SleepClass {
public static void main(String[] args) {
SleepClass s= new SleepClass();
s.m2(500);
s.m2(1000);
}

public void m2(int time) {
SleepClass s= new SleepClass();
new Thread(() -> {
s.m1(time);
}).start();
}

public void m1(int time) {

for(int i = 0; i<= 10; i++) {
System.out.println(i);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}

Are methods called from a separate thread, run on the calling thread?

will someMethod() also run on the new thread that I just created because I'm calling it from there?

Yes, that is exactly what happens. The method is just code. It's independent of the thread-of-control that happens to be running in it at a given point and time. This also means that there could be multiple threads executing that code at any given point in time if there are multiple cpu/cores.

Calling methods from a running Thread

If I was to call inner methods of the Thread, would it still run on a separate thread?

No. Threads aren't magic. When you call a method you are calling that method with the current thread. To fork a thread you actually have to create a thread object (or executor service) and start it. Then it calls run(), etc..

So if you called player.pause() you would be calling pause from the current thread which is possibly the "main" thread. Your playerThread would be doing something else in the background. The whole reason why the pause() method is synchronized is so you can all it from the outside thread and the playerThread without them overlapping. It also means that multiple threads can test and set the isPlaying boolean and other threads will see the updates.

You should most likely start with the Java thread tutorial.



Related Topics



Leave a reply



Submit