问题
I have the following code:
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);
}
}
This prints:
In run: Thread-0
Setting value main
Setting value Thread-0
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?
回答1:
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
来源:https://stackoverflow.com/questions/38253451/how-main-thread-runs-before-this-thread