In java Synchronized lock usage

An important concept in synchronized Java thread synchronization.

java is synchronized keyword, a synchronization lock, the object of its role are the following:

① action of the object. The code block in the code block is called a synchronization code blocks, scope braces {..} is enclosed code, the role of this object is to call the code block

The method ②

③ static method

④ class

Case column 1, the synchronization code block

```

public class MySynchornized implements Runnable {

private static int count;

public MySynchornized() {
count = 0;
}

@Override
public void run() {
// 同步代码块
synchronized (this) {
for (int i = 0; i < 5; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

public int getCount() {
return count;
}
}

transfer

Test Results:

Unlocked the case:

Lock:

 

Guess you like

Origin www.cnblogs.com/romulus/p/10962138.html