In the previous article, we talked about how multithreading handles shared resources and the important mechanism by which they rely on mutually exclusive access to resources: Object locks.
In this article, we take a look at the traditional synchronization implementation and the rationale behind it.
Many people know that in Java multithreaded programming, there is an important keyword, synchronized. But a lot of people will be confused when they see this: "It's all said that the synchronization mechanism is implemented through object locks, but such a keyword, I do not see the Java program locked which object ah?" “
Yes, I was puzzled and puzzled about the problem at first. But fortunately, we have the following routine:
1 public class ThreadTest extends Thread {
2
3 private int threadNo;
4
5 public ThreadTest(int threadNo) {
6 this.threadNo = threadNo;
7 }
8
9 public static void main(String[] args) throws Exception {
10 for (int i = 1; i < 10; i++) {
11 new ThreadTest(i).start();
12 Thread.sleep (1);
13 }
14 }
15
16 @Override
17 public synchronized void run() {
18 for (int i = 1; i < 10000; i++) {
19 System.out.println("No." + threadNo + ":" + i);
20 }
21 }
22 }
The program actually lets 10 threads count from 1 to 9999 on the console. Ideally, we want to see a thread count, and then the other thread to start counting. But the execution of the program tells us that the threads are still in a mess and there is no rule whatsoever.
But attentive readers note that the Run method adds a synchronized keyword, and that these threads should be able to execute the Run method one after the other.
But, as we mentioned in the previous article, the Synchronized keyword for a member method is actually a lock on the object itself that is the member method. In this case, it is a specific object of the ThreadTest class, that is, the thread itself is locked as an object. Altogether 10 threads, each holding the object lock of its own thread object. This must not produce the effect of synchronization. In other words, if these threads are to be synchronized, the object locks held by these threads should be shared and unique!