Java object lock and object transfer

Source: Internet
Author: User

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.

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.