通过扩展Thread类来创建线程

时间:2018-12-10 04:28:40

标签: 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. 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 个答案:

答案 0 :(得分:1)

Count有这一行:

while ( 1 ) {  
    if ( fread(&pn, sizeof(int), 1, fp) < 1 ) break;
    fread(&quantity, sizeof(int), 1, fp);
    fread(&price, sizeof(float), 1, fp);
    printf("%5d\t%8d\t$ %9.2f\n", pn, quantity, price);
}

您的主程序有这一行:

Thread.sleep(1000);

很显然,您将获得每3计数打印2张主打印。这就是0和1彼此相邻的原因。

关于为什么要在计数打印之前看到主打印的原因,您可以看到以下内容:

Thread.sleep(1500);

您已经解雇了Count c = new Count(); try { while (c.isAlive()) { System.out.println("main thread is alive untill child thread is alive"); Thread.sleep(1500); ,但是直到JVM执行上下文切换以实际运行该线程之前,您可能看不到结果。事实是,在某些系统上,您可能会在此之前查看计数器。通常,因为它离开始时还很近并且还没有屈服,所以您会在柜台前看到主要印刷品。

第二部分,您的c继续打印,因为它有一个循环,告诉您可以打印直到计数器线程不再活动为止。它们都使用main thread is...,因此当您查看控制台时,它们都在那看到。