主线程如何在此线程之前运行? [英] How main thread runs before this thread?

查看:73
本文介绍了主线程如何在此线程之前运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    public class Derived implements Runnable {
        private int num;

        public synchronized void setA(int num) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println("Setting value " + Thread.currentThread().getName());
            this.num = num;
        }

    @Override
    public void run()
    {
        System.out.println("In run: " + Thread.currentThread().getName());
        setA(20);
    }

        public static void main(String[] args) {
            Derived obj = new Derived();
            Thread t1 = new Thread(obj);
            t1.start();
            obj.setA(32);
        }
    }

打印:

In run: Thread-0
Setting value main
Setting value Thread-0

我的问题是,如果我先启动线程 't1',然后它进入 run 方法,如输出所示,如果对象被 t1 锁定,主线程为什么能够在 't1' 之前调用 setA?(或者甚至在锁定 'obj' main 之前就可以锁定)是调度程序还是我认为错了?

My question is if I started the thread 't1' first, and it entered the run method as the output shows, how come main thread was able to call setA before 't1' if the object was locked by t1? (or even before getting a lock on 'obj' main was able to get a lock) Is it just the scheduler or am I thinking it wrong?

推荐答案

如果对象被 t1 锁定,为什么主线程能够在 't1' 之前调用 setA?

how come main thread was able to call setA before 't1' if the object was locked by t1?

使用多线程的全部意义在于允许每个线程中的代码独立运行.Thread.start()(或任何方法)不是即时的.这需要时间,当您的线程启动时,您可以在当前线程中运行代码,实际上它甚至可以在后台线程启动之前运行完成.

The whole point of using multiple threads is to allow code in each thread to run independently. The Thread.start() (or any method) is not instantaneous. It take time and while your thread is starting, you can run code in your current thread, in fact it can run to completion before your background thread even starts.

难道只是调度器

这是其中的一部分.但这也是一个事实,即启动 Thread 不是免费的,并且需要花费大量时间.

That is part of it. But it's also the fact that starting a Thread isn't free and takes a non-trivial amount of time.

public class Test {
    public static void main(String[] args) {
        long start = System.nanoTime();
        new Thread(() -> System.out.println("Thread took " +
                (System.nanoTime() - start) / 1e6 + " ms to start"))
                .start();
    }
}

我的机器速度很快,但是当我运行这个程序来启动第一个线程需要一段时间.

I have a fast machine but when I run this program to start the first thread takes a while.

Thread took 44.695419 ms to start

这篇关于主线程如何在此线程之前运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆