Brief introduction
Multiple threads, each thread can get its own specified lock, after acquiring the lock, execute the contents of the Ysnchronized method body.
Code
public class demo2 {private static int num = 0;/*static*/public synchronized void prinnum (String tag) {try {if (Tag.equals ("a")) {num = 100; System.out.println ("tag a, set num over!"); Thread.Sleep (1000);} else {num = 200; System.out.println ("tag b, set num over!");} System.out.println ("tag " + tag + ", num = " + num); catch (exception e) {e.printstacktrace ();}} Watch the Run method output order Public static void main (String[] args) {// two different objects final demo2 d1 = new demo2 (); Final demo2 d2 = new demo2 (); Thread t1 = new thread (new runnable () {@Overridepublic void run () {d1.prinnum ("a");}); Thread t2 = new thread (new runnable () {@OvErridepublic void run () {d2.prinnum ("B");}); T1.start (); T2.start ();}}
Effect: Figure 1
650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M02/8E/34/wKiom1i4JiKg2Ap1AAAUS3T-ndg081.png "title=" 6j$ 5tx459qry7]{oa91s$82.png "alt=" Wkiom1i4jikg2ap1aaaus3t-ndg081.png "/>
On the Printnum method, add static,public synchronized static void Prinnum (String tag) {...} : Figure 2
650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/8E/34/wKiom1i4Jpvi1RLmAAAW-VgWDdk601.png "title=" 1qwk3l@cec@vky37sq0v7{d.png "alt=" Wkiom1i4jpvi1rlmaaaw-vgwddk601.png "/>
Analysis Notes
The lock acquired by the keyword synchronized is an object lock , not a piece of code (method) as a lock, so which thread in the code above executes the method of the Synchronized keyword first, which thread holds the lock (lock) of the object to which the method belongs, and two objects , the thread gets two different locks, and they don't affect each other.
In one case, the same lock, which is the Synchronized keyword on a static method, indicates a lock. Class class, type-level lock (exclusive. Class)
This article is from "I Love Big gold" blog, please be sure to keep this source http://1754966750.blog.51cto.com/7455444/1902798
Concurrent Programming (2): Multiple threads more than one lock