在已经工作的线程中调用方法时会发生什么?

Zyz*_*zyx 3 java multithreading loops while-loop

在它下面运行我的测试代码似乎在它仍在执行时调用线程方法在线程当前执行之间运行方法.我想知道的是究竟发生了什么?

线程是否暂停while循环,执行方法,然后返回循环?它是在while代码的末尾或其间的任何地方吗?

或者该方法是否在另一个单独的线程中执行?还是别的什么?

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++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 11

调用的所有方法都使用当前线程来处理所有对象.如果在Thread其上调用方法,也会像当前线程上的任何其他方法一样调用该方法.

唯一有点混乱的是start()启动另一个线程并调用run()该新线程.

这是最好不延伸Thread但是传递Runnable给它的原因之一,因为这些方法往往不做他们看起来的事情,或者你得到你不期望的副作用.

注意:Java通常在堆上有一个代理对象,用于管理实际上脱离堆(本机)的资源.例如,直接ByteBuffer或JTable或Socket或FileOutputStream.这些对象不是操作系统理解它们的实际资源,而是Java使用的对象,可以更容易地从Java代码管理/操作资源.

  • @MichaelBerry我经常点击刷新以查看最新的问题,我认为这意味着我可能会更快地看到问题.我应该回答已经持续几分钟的问题......;) (2认同)
  • IMO,很多新手都不理解_thread_和`Thread`对象之间的区别.它可能有助于解释`start()`是`Thread`方法_creates_实际线程,而其他`Thread`方法用于管理该线程. (2认同)