Object locks and object passing in Java

Source: Internet
Author: User

1. Object passing

In Java parameter passing, there are two types, the first is the basic type pass, such as int,float,double, this is the value of the pass, and the other is the object passing, such as a string or a custom class, this is a reference pass.

In other words, the base type passes a copy, and the object passes the object itself.


2. Lock

In Java, the concept of object lock is to lock the object, each object will have a memory lock, if you add a lock, you can only have one thread to operate, until the operation is complete, the other thread will not be able to re-operate the 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 incoming object and no other thread can manipulate */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 stubcom Mon common=new Common ();/* object passed, is a reference pass, that 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, will first output start and then wait 10 seconds, continue to output over, and then repeat, indicating that the object is locked

Object locks and object passing in Java

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.