Java multi-thread

  • This series of blog posts are notes for learning about Java multithreading

A deadlock

  • A situation in which two or more threads are waiting for each other to release some shared resources, and each thread is waiting for the other thread to release some shared resources. When a synchronized block has “locks on more than two objects” at the same time, deadlock may occur again
public class DeadLock {
    public static void main(String[] args) {
        MakeUp g1 = new MakeUp(0.Cinderella);
        MakeUp g2 = new MakeUp(1.Snow White); g1.start(); g2.start(); }}class Lipstick{}class Mirror{}class MakeUp extends Thread{

    // There is only one copy of the resource, so we use global variables
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choose;
    String name;

    MakeUp(int choose,String name){
        this.choose = choose;
        this.name = name;
    }
    @Override
    public void run(a){
        try {
            makeup();
        } catch(InterruptedException e) { e.printStackTrace(); }}private void makeup(a) throws InterruptedException {
        if (choose == 0) {
            synchronized (lipstick){
                System.out.println(this.name+"Get the lipstick lock.");
                Thread.sleep(1000);
                synchronized (mirror){
                    System.out.println(this.name+"Get the lock of the mirror."); }}}else {
            synchronized (mirror){
                System.out.println(this.name+"Get the lock of the mirror.");
                Thread.sleep(2000);
                synchronized (lipstick){
                    System.out.println(this.name+"Get the lipstick lock.");
                }
            }
        }
    }

}
Copy the code

Here I compare G1 and G2 to two little sisters doing makeup on their own dressers, which look exactly the same, but they share the lipstick and mirror. When G1 locks the lipstick, it actually locks the entire dresser she’s on, but since the lipstick and mirror are shared, when she locks her own lipstick, G2 finds that her own lipstick is also locked. Mirrors work the same way.

  • There are four necessary conditions for a deadlock:

    1. Mutually exclusive condition: a resource can only be used by one process at a time.

    2. Request and hold conditions: when a process is blocked by requesting resources, it holds on to acquired resources

    3. Non-dispossession condition: a process cannot forcibly take away a resource it has acquired until it is used up

    4. Circular waiting condition: a circular waiting resource relationship is formed between several processes

The Lock (Lock)

  • Starting with JDK5.0, Java provides a more powerful thread synchronization mechanism – synchronization is achieved by explicitly defining a synchronization lock object. A synchronous Lock is acted by using a Lock object.
  • Java. Util. Concurrent. The locks. Lock interface is the tool of control multiple threads to Shared resources access. A Lock provides exclusive access to a shared resource. Only one thread at a time can Lock the Lock object. The thread must acquire the Lock object before starting to access the shared resource
  • The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized. In the implementation of thread-safe control, ReentrantLock is more commonly used, which can display Lock, Lock release.
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
        newThread(testLock2).start(); }}class TestLock2 implements Runnable{
    int ticketNums = 10;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run(a) {
        while (true){
            lock.lock();
            try {
                if (ticketNums>0) {try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                } else {
                    break; }}finally{ lock.unlock(); }}}}Copy the code

The difference between synchronized and Lock

  • Lock is an explicit Lock (manually open and close the Lock, do not forget to close the Lock) synchronized is an implicit Lock, released automatically when out of scope
  • Lock has code block locks, synchronized has code block and method locks
  • Lock locks, the JVM takes less time to schedule threads and performs better. And more extensible (more subclasses can be provided)
  • The order of preference
    1. Lock
    2. Synchronized code block (already in method body, allocated resources)
    3. Synchronous methods (outside the method body)