在下面运行我的测试代码,看来在仍在执行时调用线程方法会在当前执行的线程之间运行该方法。 我想知道到底是什么情况?
线程是否暂停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++;
}
}
}
和
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);
}
}
答案 0 :(得分:11)
所有调用的方法都将当前线程用于所有对象。如果您在Thread
上调用方法,它也将像当前线程上的其他方法一样调用该方法。
唯一有点混乱的地方是start()
启动另一个线程并为该新线程调用run()
。
这是最好不要扩展Thread
而是将Runnable
传递给它的原因之一,因为这些方法经常不执行它们所显示的作用,或者您会产生副作用没想到。
注意:Java通常在堆上有一个代理对象,用于管理实际上不在堆上的资源(本机)。例如。直接ByteBuffer或JTable或Socket或FileOutputStream。这些对象并不是操作系统可以理解的实际资源,而是Java使用的对象,它使Java代码中的资源管理/操作变得更加容易。
答案 1 :(得分:4)
发生了什么:主线程完成了所有这些操作:
thred.start(); // start another thread
Thread.sleep(10000); // sleep
while (true) {
System.out.println("doing it");
thred.other(); // invoke a method on some object
意思是: other 线程运行其run()
方法,没有其他方法。
在您的代码中,您的 main 线程仅在该线程对象上调用另一个方法。它仍然在主线程上发生!