简体   繁体   中英

What happens when you call a method in a thread that is already working?

Running my test code below it appears that calling a threads method while it is still executing runs the method between the threads current execution. What I'm wondering is what is exactly happening?

Does the thread pause the while loop, execute the method, and then go back to the loop? Does it do so at the end of the while code or anywhere in between?

Or does the method execute in another separate thread? Or something else altogether?

package test;

public class main {
    public static threed thred = new threed();

    public static void main(String[] args) throws InterruptedException {
        thred.start();
        Thread.sleep(10000);
        while (true) {
            System.out.println("doing it");
            thred.other();
            Thread.sleep(2000);
            thred.x++;
        }
    }
}

and

package test;

public class threed extends Thread {
    public int x;

    public threed() {
        x = 0;
    }

    public void run() {
        while (x < 10) {
            System.out.println(x);          
        }   
    }

    public void other() {
        System.out.println("other " + x);
    }
}

All methods called are using the current thread for all objects. If you call a method on Thread it also calls that method like any other on the current thread.

The only one which is slightly confusion is that start() starts another thread and calls run() for that new thread.

This is one of the reasons it is best not to extend Thread but pass a Runnable to it as too often the methods either don't do what they appear to or you get side effects you don't expect.

NOTE: Java often has a proxy object on the heap for managing a resources which is actually off heap (native). Eg direct ByteBuffer or JTable or Socket or FileOutputStream. These objects are not the actual resource as the OS understands them, but an object Java uses to make it easier to manage/manipulate the resource from Java code.

What happens: the main thread does all of this:

thred.start(); // start another thread
Thread.sleep(10000); // sleep
while (true) {
   System.out.println("doing it"); 
   thred.other(); // invoke a method on some object

Meaning: the other thread runs its run() method, nothing else.

In your code, your main thread simply invokes another method on that thread object. It is still happening on the main thread!

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