一旦子线程完成执行,它会恢复执行主线程的代码行吗?

huangapple 未分类评论51阅读模式
标题翻译

Once child thread completes its execution, will it resume executing main thread lines?

问题

以下是翻译好的部分:

我正在尝试在主线程中创建一个子线程,如下所示:

public class test {
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("在普通子线程中:" + Thread.currentThread().getName());

            }
        });
        t1.start();
        System.out.println("主线程休眠 5 秒:" + Thread.currentThread().getName());
        Thread.sleep(5000);
        System.out.println("在主线程中:" + Thread.currentThread().getName());
        System.out.println("退出主线程:" + Thread.currentThread().getName());
    }
}

在上面的示例中,我让主线程休眠了 5 秒。因此,一旦子线程完成打印其 sysout 语句,我期望以下这些代码行将会被执行两次:

System.out.println("在主线程中:" + Thread.currentThread().getName());
System.out.println("退出主线程:" + Thread.currentThread().getName());

但是当我执行该程序时,我只看到这些代码行被执行了一次。

如果我的期望是正确的,请告诉我。我期望主线程应该执行这些 sysout 语句两次。

英文翻译

I am trying to create a child thread in a main thread as below,

public class test {
	public static void main(String[] args) throws InterruptedException {

		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println("In normal child thread " + Thread.currentThread().getName());

			}
		});
		t1.start();
		System.out.println("main thread sleeping for 5 seconds : " + Thread.currentThread().getName());
		Thread.sleep(5000);
		System.out.println("In main thread : " + Thread.currentThread().getName());
		System.out.println("exiting main thread : " + Thread.currentThread().getName());
	}

}

In the above example, i have made main thread sleep for 5 seconds. So once the child thread completes printing its sysout statement, I am expecting below lines to be executed twice,

System.out.println("In main thread : " + Thread.currentThread().getName());
System.out.println("exiting main thread : " + Thread.currentThread().getName());

But when i execute the program, i see only once these lines are executed.

Please update me if my expectation is right? . I am expecting main thread should execute these sysout statements twice.

答案1

得分: 0

这里我们运行了两个线程:MainThread(主线程)和Child thread(子线程)。当我们调用子线程的start()方法时,run()方法中的逻辑被执行。
这个子线程会在其run方法被执行时终止。
主线程会继续执行其余的代码。

英文翻译

Here we're running two threads: the MainThread and the Child thread. When we invoke the start() method for the child thread(), the logic in the run() method is executed.
This child thread will die when its run method is executed.
The main thread continues with its execution of the remaining code.

huangapple
  • 本文由 发表于 2020年5月30日 20:57:01
  • 转载请务必保留本文链接:https://java.coder-hub.com/62102751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定