How main thread runs before this thread?

后端 未结 1 1209
心在旅途
心在旅途 2021-01-29 09:30

I have the following code:

    public class Derived implements Runnable {
        private int num;

        public synchronized void setA(int num) {
                     


        
相关标签:
1条回答
  • 2021-01-29 10:17

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

    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.

    Is it just the scheduler

    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
    
    0 讨论(0)
提交回复
热议问题