The problem that I am facing in a complex Java application boils down to following: the main thread does not proceeds until the sub-thread is not finished, although I thought that it should. The code that exemplifies the problem is shown below:
public class ThreadTest {
static class MyThread extends Thread{
public void run(){
for(double i = 0; i<1; i+=0.01){
System.out.println(Math.pow(Math.PI,Math.E)*100.0*i-234.0);
}
}
}
public static void main(String[] args){
(new MyThread()).run();
System.out.println("main thread");
}
}
When I run this program, I always get the output from MyThread first (independently how many steps are in the cycle), and then I get the message from the main thread. The idea of creating threads is to execute code asynchronously, but here I observe a clearly sync behavour. What do I miss?
Thanks in advance!
When you call run(), you are calling the run() method in the current thread!. In the same manner as if you called any other method for another object.
If you want a new thread to call run(), you need to call start() on the thread.
try
new MyThread().start();
One way to prove this to yourself is to step through your program in a debugger, this would show that the there is only one thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With