java - 通过扩展Thread类创建线程

标签 java multithreading

这是一个通过扩展 Thread 类创建线程的简单示例。

class Count extends Thread {

    Count() {
        super("my extending thread");
        System.out.println("my new thread is started " + this);
        start();
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println("count " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("my thread run is over");
        }
    }

}

public class Multi2 {

    public static void main(String[] args) {
        Count c = new Count();
        try {
            while (c.isAlive()) {
                System.out.println("main thread is alive untill child thread is alive");
                Thread.sleep(1500);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("main thread is over");
        }
    }
}

我的输出是这样的。

my new thread is started Thread[my extending thread,5,main]
main thread is alive untill child thread is alive
count 0
count 1
main thread is alive untill child thread is alive
count 2
main thread is alive untill child thread is alive
count 3
count 4
main thread is alive untill child thread is alive
count 5
main thread is alive untill child thread is alive
count 6
count 7
main thread is alive untill child thread is alive
count 8
main thread is alive untill child thread is alive
count 9
my thread run is over
main thread is over

我的问题是,


01. 为什么主线程处于 Activity 状态直到子线程处于 Activity 状态
计数0之前打印输出 数1

02.为什么主线程处于 Activity 状态直到子线程处于 Activity 状态输出在run()方法的输出中保持打印?

请帮我解决这个问题。
谢谢。

最佳答案

计数有这一行:

Thread.sleep(1000);

你的主程序有这一行:

Thread.sleep(1500);

显然,每打印 3 份打印品,您将获得 2 份主要打印品。这就是 0 和 1 彼此相邻的原因。

至于为什么在计数打印之前看到主打印,可以看这个:

Count c = new Count();
try {
while (c.isAlive()) {
    System.out.println("main thread is alive untill child thread is alive");
    Thread.sleep(1500);

您已经启动了 c,但在 JVM 执行上下文切换以实际运行该线程之前,您可能看不到结果。事实上,在某些系统上,您可能会在此之前看到您的计数器。通常,因为距离开始时间很近而且尚未产生,所以您会在柜台前看到主要打印品。

对于第二部分,您的主线程是...继续打印,因为它有一个循环告诉它打印,直到您的计数器线程不再 Activity 。它们都使用 System.out,因此当您查看控制台时,您会看到它们都在那里。

关于java - 通过扩展Thread类创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53699512/

相关文章:

android - 当应用程序进入后台时暂停线程

java - 从多行解析java中的输入

java - 什么是类路径以及如何设置它?

java - Java中copyOf方法的奇怪返回值

java.sql.Connection 在线程内不可见

C++ 11 替代 pthread_cond_timedwait

java - 有关如何改进当前模糊搜索实现的建议

java - 这就是您在服务层中调用 Dao 的方式吗?

multithreading - 多线程人脸检测停止工作

c# - 调度程序计时器错误