首页 文章

通过扩展Thread类创建线程

提问于
浏览 759 次
0

这是一个关于通过扩展 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.之前如何打印 main thread is alive untill child thread is alive 输出
count 0 count 1

02.如何 main thread is alive untill child thread is alive 输出保持打印 run() 方法的输出?

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

1 回答

  • 1

    伯爵有这条线:

    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执行上下文切换以实际运行该线程之前,你可能看不到结果 . 事实是,在某些系统上,您可能会在此之前看到您的柜台 . 通常,因为它还没有产生,你会看到柜台前的主要印刷品 .

    对于你的第二部分,你的 main thread is... 保持打印,因为它有一个循环告诉它打印,直到你的计数器线程不再存在 . 他们都使用 System.out 所以当你看着你的控制台时,你会看到它们 .

相关问题