开发者

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜