public class Lock02 {
private int i = 0;
public static void main(String[] args) {
Object o = new Object();
Lock02 lock = new Lock02();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
synchronized (o) {
lock.i++;
String name = Thread.currentThread().getName();
System.out.println(lock.i +" :: "+ name);
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
synchronized (o) {
lock.i++;
String name = Thread.currentThread().getName();
System.out.println(lock.i +" :: "+ name);
}
}
}).start();
}
}
這是物件鎖的測驗 為什么列印結果竟然是交錯的
1 :: Thread-0
2 :: Thread-0
3 :: Thread-1
4 :: Thread-1
5 :: Thread-1
6 :: Thread-1
7 :: Thread-1
不是獲取一個物件鎖 方法不執行完 鎖不釋放嗎 這里好像是鎖釋放了??? 為什么會這樣
uj5u.com熱心網友回復:
你把synchronized(o)放到for前面再試試就知道了。離開了synchronized(o){}的花括號,鎖就自動放開了。你是在for里面拿鎖的,所以每次進入回圈兩個執行緒都要重新搶鎖,搶到鎖的就有機會執行一次回圈;而如果synchronized(o)放在for回圈前,就能保證搶到鎖后把for回圈執行完才釋放鎖。這是不一樣的。
uj5u.com熱心網友回復:
synchronized有兩種使用方式,一種是同步方法(包含靜態和非靜態方法),一種是同步代碼塊.JVM在實作時會在常量池的method_info中增加ACC_SYNCHRONIZED標志來標記方法是同步方法,使用了 monitorenter 和 monitorexit 指令來實作同步代碼塊.當遇到ACC_SYNCHRONIZED或者monitorenter時,也就是說當某個執行緒A執行同步方法或者同步代碼塊前,執行緒A會獲取鎖物件的Monitor占有權,如果獲取不成功,就處于Thread.State.BLOCKED狀態,如果獲取成功,就執行同步方法或者同步代碼塊內代碼,執行完代碼或者遇到例外就釋放Monitor占用權.簡化的來說就是獲取鎖->執行代碼->釋放鎖. 回到你的問題,執行緒0首先搶到鎖物件的Monitor占有權,開始執行代碼,而同時執行緒1沒有獲取到鎖物件的Monitor占有權,就處于阻塞狀態等待獲取到鎖物件的Monitor占有權,執行緒0執行完一次同步代碼塊中代碼后,釋放鎖物件的Monitor占有權,執行緒0和執行緒1開始搶占鎖物件的Monitor占有權,然后是搶到鎖物件的Monitor占有權的執行緒繼續執行同步代碼塊中的代碼,重復這個程序,從你貼的結果來看,前2次是執行緒0搶到了,而后面是執行緒1搶到了.
public class Lock02 {
public static synchronized void function1() {
}
public static void function2() {
}
public void function3() {
synchronized (Lock02.class) {
}
}
}
下面是使用javap -c -v 反編譯我的Lock02出來的部分資訊,因為有點長,有些資訊我已經洗掉了
public class Lock02
{
public static synchronized void function1();
descriptor: ()V
flags: ACC_PUBLIC, ACC_STATIC, ACC_SYNCHRONIZED //注意這里的ACC_SYNCHRONIZED
Code:
stack=0, locals=0, args_size=0
0: return
LineNumberTable:
line 13: 0
public synchronized void function2();
descriptor: ()V
flags: ACC_PUBLIC, ACC_SYNCHRONIZED //注意這里的ACC_SYNCHRONIZED
Code:
stack=0, locals=1, args_size=1
0: return
LineNumberTable:
line 16: 0
public void function3();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=2, locals=3, args_size=1
0: ldc #2 // class Lock02
2: dup
3: astore_1
4: monitorenter //注意這里的monitorenter
5: aload_1
6: monitorexit //注意這里的monitorexit
7: goto 15
10: astore_2
11: aload_1
12: monitorexit
13: aload_2
14: athrow
15: return
}
原文:
"
instructions. When invoking a method for which ACC_SYNCHRONIZED is set, the executing thread enters a monitor, invokes the method itself, and exits the monitor whether the method invocation completes normally or abruptly. During the time the executing thread owns the monitor, no other thread may enter it. If an exception is thrown during invocation of the synchronized method and the synchronized method does not handle the exception, the monitor for the method is automatically exited before the exception is rethrown out of the synchronized method.
Synchronization of sequences of instructions is typically used to encode the synchronized block of the Java programming language. The Java Virtual Machine supplies the monitorenter and monitorexit instructions to support such language constructs. Proper implementation of synchronized blocks requires cooperation from a compiler targeting the Java Virtual Machine (§3.14).
"
原文
"
monitorenter
Operation
Enter monitor for object
Format
monitorenter
Forms
monitorenter = 194 (0xc2)
Operand Stack
..., objectref →
...
Description
The objectref must be of type reference.
Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:
If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
If another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is zero, then tries again to gain ownership.
Run-time Exception
If objectref is null, monitorenter throws a NullPointerException.
Notes
A monitorenter instruction may be used with one or more monitorexit instructions (§monitorexit) to implement a synchronized statement in the Java programming language (§3.14). The monitorenter and monitorexit instructions are not used in the implementation of synchronized methods, although they can be used to provide equivalent locking semantics. Monitor entry on invocation of a synchronized method, and monitor exit on its return, are handled implicitly by the Java Virtual Machine's method invocation and return instructions, as if monitorenter and monitorexit were used.
The association of a monitor with an object may be managed in various ways that are beyond the scope of this specification. For instance, the monitor may be allocated and deallocated at the same time as the object. Alternatively, it may be dynamically allocated at the time when a thread attempts to gain exclusive access to the object and freed at some later time when no thread remains in the monitor for the object.
The synchronization constructs of the Java programming language require support for operations on monitors besides entry and exit. These include waiting on a monitor (Object.wait) and notifying other threads waiting on a monitor (Object.notifyAll and Object.notify). These operations are supported in the standard package java.lang supplied with the Java Virtual Machine. No explicit support for these operations appears in the instruction set of the Java Virtual Machine.
monitorexit
Operation
Exit monitor for object
Format
monitorexit
Forms
monitorexit = 195 (0xc3)
Operand Stack
..., objectref →
...
Description
The objectref must be of type reference.
The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.
The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.
Run-time Exceptions
If objectref is null, monitorexit throws a NullPointerException.
Otherwise, if the thread that executes monitorexit is not the owner of the monitor associated with the instance referenced by objectref, monitorexit throws an IllegalMonitorStateException.
Otherwise, if the Java Virtual Machine implementation enforces the rules on structured locking described in §2.11.10 and if the second of those rules is violated by the execution of this monitorexit instruction, then monitorexit throws an IllegalMonitorStateException.
Notes
One or more monitorexit instructions may be used with a monitorenter instruction (§monitorenter) to implement a synchronized statement in the Java programming language (§3.14). The monitorenter and monitorexit instructions are not used in the implementation of synchronized methods, although they can be used to provide equivalent locking semantics.
The Java Virtual Machine supports exceptions thrown within synchronized methods and synchronized statements differently:
Monitor exit on normal synchronized method completion is handled by the Java Virtual Machine's return instructions. Monitor exit on abrupt synchronized method completion is handled implicitly by the Java Virtual Machine's athrow instruction.
When an exception is thrown from within a synchronized statement, exit from the monitor entered prior to the execution of the synchronized statement is achieved using the Java Virtual Machine's exception handling mechanism (§3.14).
"
uj5u.com熱心網友回復:
public class Test2 {private int i = 0;
public static void main(String[] args) {
Object o = new Object();
Test2 lock = new Test2();
new Thread(() -> {
synchronized (o) {
for (int i = 0; i < 100; i++) {
lock.i++;
String name = Thread.currentThread().getName();
System.out.println(lock.i +" :: "+ name);
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
synchronized (o) {
lock.i++;
String name = Thread.currentThread().getName();
System.out.println(lock.i +" :: "+ name);
}
}
}).start();
}
}
uj5u.com熱心網友回復:
synchronized 一個是鎖代碼塊,一個是鎖方法;你要鎖住for整個代碼塊才能達到你要的效果轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/12751.html
標籤:Java SE
下一篇:基于Java的倉庫管理系統
