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代码管理/操作资源.
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |