In the previous section, we have learned about the commonly used keyword synchronized in Java multithreaded programming and the object locking mechanism associated with it. In this section, let's understand the lock mechanism in the newly introduced concurrency framework in JDK 5.
I think a lot of the friends who bought the Java Programmer interview book and so on, must be very familiar with the following question:
Q: Please compare the similarities and differences between synchronized and Java.util.concurrent.locks.Lock.
Answer: The main similarities: lock can complete all the functions implemented by synchronized
Main differences: Lock has more precise line Cheng and better performance than synchronized. Synchronized will automatically release the lock, and lock must require the programmer to manually release it, and must be released in the finally clause.
Well, let's first despise the exam-oriented education.
To start with, let's look at a multithreaded program. It uses multiple threads to access a student object, changing the value of the variable. We first use the traditional synchronized mechanism to achieve it:
public class Threaddemo implements Runnable {
Class Student {
private int age = 0;
public int getage () {
return age;
}
public void Setage (int age) {
This.age = age;
}
}
Student Student = new Student ();
int count = 0;
public static void Main (string[] args) {
Threaddemo td = New Threaddemo ();
thread T1 = new Thread (TD, "a");
Thread t2 = new Thread (TD, "B");
thread t3 = new Thread (TD, "C");
T1.start ();
T2.start ();
T3.start ();
}
public void Run () {
Accessstudent ();
}
public void Accessstudent () {
String currentthreadname = Thread.CurrentThread (). GetName ();
System.out.println (Currentthreadname + "is running!");
Synchronized (this) {//(1) uses the same Threaddemo object as a synchronous lock
System.out.println (Currentthreadname + "got lock1@step1!");
try {
count++;
Thread.Sleep (5000);
catch (Exception e) {
E.printstacktrace ();
finally {
System.out.println (Currentthreadname + "A-Reading count:" + count);
}
}
System.out.println (currentthreadname + "release lock1@step1!");
Synchronized (this) {//(2) uses the same Threaddemo object as a synchronous lock
System.out.println (Currentthreadname + "got lock2@step2!");
try {
Random Random = new Random ();
int age = Random.nextint (100);
SYSTEM.OUT.PRINTLN ("thread" + Currentthreadname + "set Age to:" + age);
This.student.setAge (age);
SYSTEM.OUT.PRINTLN ("thread" + Currentthreadname + "The" "The" "The" "the" "+ This.student.getAge ()");
Thread.Sleep (5000);
catch (Exception ex) {
Ex.printstacktrace ();
} finally{
SYSTEM.OUT.PRINTLN ("thread" + Currentthreadname + "Second Read Age is:" + this.student.getAge ());
}
}
System.out.println (currentthreadname + "release lock2@step2!");
}
}