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

Zyzyx :

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);
    }
}
Peter Lawrey :

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). E.g. 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84520&siteId=1