我有关线程的问题不太明白,特别是在使用Java和Android时。
假设我有一个名为A
的线程,它启动了线程B
。如果线程A
停止了,那么线程B
仍然会继续运行。这是怎么实现的?线程B
属于谁?主线程吗?
Thread类
public class ParentThread extends Thread {
public void run(){
Log.e("PARENT THREAD", "STARTS RUNNING");
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
Log.e("CHILD THREAD", "IS ALIVE");
try {
Thread.sleep(1000);
}
catch (InterruptedException exc) {
e.printStackTrace();
}
}
}
}).start();
Log.e("PARENT THREAD", "STOPS RUNNING");
}
}
活动
new ParentThread().start();
Logcat 输出
01-07 13:45:16.726 22063-22081/? E/PARENT THREAD: STARTS RUNNING
01-07 13:45:16.726 22063-22081/? E/PARENT THREAD: STOPS RUNNING
01-07 13:45:16.727 22063-22082/? E/CHILD THREAD: IS ALIVE
01-07 13:45:17.727 22063-22082/? E/CHILD THREAD: IS ALIVE
01-07 13:45:18.727 22063-22082/? E/CHILD THREAD: IS ALIVE
01-07 13:45:19.727 22063-22082/? E/CHILD THREAD: IS ALIVE
...
fork()
函数? - Scaraux