I have the following code:
public class Derived implements Runnable {
private int num;
public synchronized void setA(int num) {
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