Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why main thread waits for another thread to finish before proceed?

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!

like image 915
Tim Avatar asked Dec 16 '22 19:12

Tim


1 Answers

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.

like image 196
Peter Lawrey Avatar answered Apr 27 '23 00:04

Peter Lawrey