Java object lock and object transfer
1. Object Transfer
There are two types of parameter passing in JAVA. The first is basic type passing, such as int, float, and double. This is value passing, and the other is object passing, for example, String or custom class, which is passed by reference.
That is to say, the basic type is a copy, and the object is the object itself.
2. Lock
In JAVA, the object lock concept is to lock the object. Each object has a memory lock. After the lock is applied, only one thread can perform operations. Before the operation is completed, other threads cannot perform another operation on this object.
3. Example
Package com. itbuluoge. mythread; class Common {private int num; public int getNum () {return num;} public void setNum (int num) {this. num = num ;}} class SyThread extends Thread {private Common common; public SyThread (Common common) {this. common = common;} public void run () {/* locks the passed object, and other threads cannot operate */synchronized (common) {System. out. println ("start ..... "); try {this. sleep (10000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("over ..... ") ;}} public class TestThread {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubCommon common = new Common ();/* the object is passed by reference, that is, is the same object */SyThread first = new SyThread (common); SyThread second = new SyThread (common); first. start (); second. start ();}}
4. Output
Start .....
Over .....
Start .....
Over .....
5. start is output first, and then wait for 10 seconds. The output is over again, indicating that the object is locked.