Synchronization Java ---- thread

Synchronization Java ---- thread

The introduction of problem

When operating on a thread, often encounter security thread.
Here I use an example to illustrate:

package com.CharlesLC_Test;

public class Window_Test {
    public static void main(String[] args) {
        Window window = new Window();
        Thread window1 = new Thread(window);
        Thread window2 = new Thread(window);
        Thread window3 = new Thread(window);
        window1.setName("窗口一");
        window2.setName("窗口二");
        window3.setName("窗口三");
        window1.start();
        window2.start();
        window3.start();

    }

}
class Window implements Runnable{
    private int tickets = 100;
    @Override
    public void run() {
        while(true) {
            if (tickets > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":成功取票"+tickets+"还剩下" + --tickets);
            }
            else{break;}
        }
    }
}

Results: there was heavy ticket window
Here Insert Picture Description
where the problem lies:
on more than one statement only been partially implemented, have not been performed, another thread to perform involved. Lead to erroneous data sharing.

Thread synchronization mode

Use Synchronized.

When a piece of code that a synchronized thread calls the object, you need to acquire the lock, and then to execute the appropriate code, after the execution, release the lock. When a thread to get the lock, other threads can not enter this code is the lock up.

Sync block

Usage:
synchronized(对象){//需要被同步的代码;}
Here I modified the Window class tickets in this example:

class Window implements Runnable{
    private int tickets = 100;
    @Override
    public void run() {
        while(true) {
        // 这里作了改变,把这段代码用 synchronized锁了起来
            synchronized (this) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":成功取票" + tickets + "还剩下" + --tickets);
                } else {
                    break;
                }
            }
        }
    }
}

result:
Here Insert Picture Description

Synchronization method:

Instructions:
public synchronized void show(String name){ }

Modified class Window

class Window implements Runnable{
    private int tickets = 100;
    @Override
    public void run() {
        while(true) {
            show();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (tickets == 0){
                break;
            }
        }
    }

    private synchronized void show() {
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + ":成功取票" + tickets + "还剩下" + --tickets);
        }

    }
}

result:
Here Insert Picture Description

  • The current thread synchronization method, the synchronization code block execution ends.
  • The current thread encounters a break in the synchronized block, synchronization method, return to terminate the code block, to continue carrying out the method.
  • The current thread appeared untreated Error or Exception block synchronization code, the synchronization process, resulting in an abnormal end.
  • The current thread of execution object thread synchronization code block, the synchronization method wait () method, the current thread is suspended, and release the lock.
    Note : You must ensure that the use of multiple threads share a resource with a lock, this is very important, otherwise it can not guarantee the security of shared resources

Use Lock ()

Importing
import java.util.concurrent.locks.ReentrantLock;

Use:

A {class
        Private Final Lock of ReentrantLock new new ReentrantLock = ();
       public void m () {
        Lock.lock ()
        the try {
        // thread-safe code;
        the finally {
        lock.unlock ();
}

Contrast synchronized with the Lock

1.Lock explicit lock (manually opening and closing the lock, the lock do not forget to turn off), the synchronized implicit lock is automatically released out of scope
2.Lock only lock block, there are the synchronized code block lock and method lock
3. use lock locks, JVM will spend less time to schedule threads, better performance. And has better scalability (more subclasses)

Published 10 original articles · won praise 8 · views 1408

Guess you like

Origin blog.csdn.net/weixin_45640609/article/details/104553708