[英]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? 线程是否暂停while循环,执行方法,然后返回循环? Does it do so at the end of the while code or anywhere in between?
它是在while代码的末尾或其间的任何地方吗?
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. 如果在
Thread
上调用方法,它也会像当前线程上的任何其他方法一样调用该方法。
The only one which is slightly confusion is that start()
starts another thread and calls run()
for that new thread. 唯一有点混乱的是
start()
启动另一个线程并为该新线程调用run()
。
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. 这是最好不要扩展
Thread
但是将Runnable
传递给它的原因之一,因为这些方法通常不会执行它们看起来或你得到的副作用。
NOTE: Java often has a proxy object on the heap for managing a resources which is actually off heap (native). 注意:Java通常在堆上有一个代理对象,用于管理实际上脱离堆(本机)的资源。 Eg direct ByteBuffer or JTable or Socket or FileOutputStream.
例如,直接ByteBuffer或JTable或Socket或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.
这些对象不是操作系统理解它们的实际资源,而是Java使用的对象,可以更容易地从Java代码管理/操作资源。
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. 含义: 另一个线程运行其
run()
方法, 没有别的。
In your code, your main thread simply invokes another method on that thread object. 在您的代码中,您的主线程只是在该线程对象上调用另一个方法。 It is still happening on the main thread!
它仍然发生在主线程上!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.