简体   繁体   中英

The functionalities of two lines of code

I'm learning about the threads in Java. I want to know whether the following two pieces of code are the same:

 class B extends Thread {
    public void run() {
        doSomething();
    }
    public void doSomething() {}
}
class A extends Thread { 
    public void run() {
        new B().start();
    }
}

The second piece of code is changing the class A:

class A extends Thread {
        public void run() {
            new B().doSomething();
        }
}

When I read the code of my team's project, I find this problem: A thread invoking another thread without loop.

These two cases are not the same, as your question already suggests.

Assuming that in each case we enter the code by calling new A().start() , then the first example starts a thread (A) which starts another thread (B) which calls doSomething() .

The second case starts a single thread (A) which calls B.doSomething() . In this case we don't start a thread of type B, because we never call .start() on an instance of B.

In the first snippet you are actually creating a new thread and the invocation of doSomething() is in a separate thread to what A's run() method is running in,

In the second snippet you are execution B's doSomething() in the context (thread) that A is running in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM