I am trying to create a new thread with an custom object, and then call this custom objects method from the main thread. The idea is that the main thread can go on doing other stuff, while the custom object goes on working in the second thread:
public class Multithreading {
public static void main(String[] args) {
Multithreading mt = new Multithreading();
mt.multiTest();
}
public void multiTest() {
SomeObject someObject = new SomeObject();
Thread thread = new Thread(someObject);
thread.setDaemon(true);
thread.start();
someObject.startit();
int i = 0;
while (i < 3) {
try {
System.out.println("this is the main thread being busy");
Thread.sleep(3000);
i += 1;
} catch (InterruptedException e) {
}
}
}
class SomeObject implements Runnable {
public void sayHello() {
System.out.println("this is the second thread being busy");
}
public void startit() {
int i = 0;
while (i < 3) {
try {
sayHello();
Thread.sleep(3000);
i += 1;
} catch (InterruptedException e) {
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
}
The output is:
this is the second thread being busy
this is the second thread being busy
this is the second thread being busy
this is the main thread being busy
this is the main thread being busy
this is the main thread being busy
It should be more like this:
this is the second thread being busy
this is the main thread being busy
this is the second thread being busy
this is the main thread being busy
this is the second thread being busy
this is the main thread being busy
So the main Thread is blocked until the method is completed. Is the main thread waiting for completion of someObject.startit()
in the second thread(Being void as return type, I would think that this would not be the case)? Or is it executed in the first thread, therefore blocking it?
I know that with the following code I could execute someObject.startit()
in another thread, but it would be created from scratch every time, and I cant afford the thread creation overhead:
new Thread(() -> {someObject.startit();}).start();
How can one thread call methods from an object in another thread without blocking?