What exactly is the Java synchronized locked?

Source: Internet
Author: User

  刚学java的时候,仅仅知道synchronized一个线程锁。能够锁住代码,可是它真的能像我想的那样,能够锁住代码吗?  在讨论之前先看一下项目中常见关于synchronized的使用方法:
Public synchronized void Synccurrentobject () {System. out. println(Thread. CurrentThread(). GetName()+".. Start: "+"-----"+system. Currenttimemillis()); try {Thread. Sleep( +); } catch (Interruptedexception e) {E. Printstacktrace(); } System. out. println(Thread. CurrentThread(). GetName()+".. End: "+"-----"+system. Currenttimemillis()); }

This ensures that only one thread enters the method when multiple threads are interviewed. Are other threads plugged in?
I use the thread pool to create three thread capacity and start five threads, respectively:

     Public Static void synccurrentobjecttest() {Executorservice exec = Executors.newfixedthreadpool (3);//FINAL Generatecode GCode = new Generatecode ();         for(inti =0; I <5; i++) {Exec.execute (NewRunnable () {@Override                 Public void Run() {Generatecode GCode =NewGeneratecode ();                Gcode.synccurrentobject ();        }            });    } exec.shutdown (); }

Operating effect:

The input log indicates that synchronized is added to the method and not thread safe, but that multiple threads run in parallel. For example, thread 3 does not run after thread 1 has finished running. But the thread 1 sleeps when. Thread 3 obtains the lock directly. To run. So, in the original implementation. What if thread safety is guaranteed?
Workaround: When multiple threads call the synchronized decorated method, the Synchronized method is called the same object.
The detailed solution is to create a Generatecode object once (written as a singleton is better). Then call the synchronized adornment method.
Detailed changes such as the following:

Why is it possible to change this? The principle is due to the member method. Synchronized can only lock the thread of the current object, and the threads of other objects cannot be locked.

Also synchronized is placed in the method and within the method synchronize (this) is equivalent. Can only lock the current object.
But false assumptions lock multiple threads of different objects. What should I do? The demo sample code is as follows:

    //Add synchronized thread safety directly to static methods     Public synchronized Static void syncstatic() {//dosomething .}//Synchronized current class thread safety on a static method     Public  Static void Synccurrentclass() {synchronized(Generatecode.class) {//dosomething .}        }//Synchronized current class thread safety on member methods     Public   void Synccurrentobjectbythisclass() {synchronized(Generatecode.class) {//dosomething .}    }

Using synchronized to lock the current class bytecode, there is always only one thread in the current class that can go into operation, and the other threads get stuck.

Summary: Synchronized can lock the current object or lock the class.
Synchronized locks the current object's wording:
Public synchronized void A () {
}

public void ab () {
Synchronized (this) {
}
}

Synchronized locks the current class's wording:
Public synchronized static void A () {
}
public static void A () {
Synchronized (class name) {
}
}
public void ab () {
Synchronized (class name) {
}
}
My understanding is that when synchronized is acting on an object, the threads in the same object are mutually exclusive and only one thread has finished running. Another thread has the ability to get an object lock to run.

Assuming that it is not the same object, it does not produce mutually exclusive
When synchronized is acting on a class, it is mutually exclusive to call the same synchronized-modified method for multiple threads of different objects in the same JVM. Because a JVM only produces a class file.

Expand:
1. If you want threads to repel each other, is there an efficiency problem with the Synchronized method?
Theory should be a problem of efficiency, because each object has an object lock, and when one thread gets the lock, the other threads must be blocked. (not written code test)

2, assuming that the distributed system, the use of synchronized invalid. Since synchronized can only lock the current JVM's threads at most. There is nothing for the other server threads.

So how do you deal with it?
I looked up some information. Online said to be able to use zookeeper+ other components to complete the distributed lock or optimistic lock.

Because there is no detailed practice. Just read a few articles. Have no say, so interested friends can search their own java+ distributed lock

Full test Demo source code: http://download.csdn.net/download/zl544434558/9495663

What exactly is the Java synchronized locked?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.