In this chapter we discuss another use of the synchronized () code block, which can be used not only with this, but also with other objects.
1. Code Listing
Package com.ray.deepintothread.ch02.topic_13;/** * * @author Raylee * */public class Objectlock {public static void main ( String[] args) throws Interruptedexception {MyService myservice = new MyService (); Threadone Threadone = new Threadone (MyService); Thread thread = new Thread (threadone); Thread.Start (); Threadtwo threadtwo = new Threadtwo (MyService); Thread thread2 = new Thread (threadtwo); Thread2.start ();}} Class Threadone implements Runnable {private MyService myservice;public threadone (MyService myservice) {This.myservice = MyService;} @Overridepublic void Run () {try {Myservice.updatea ();} catch (Interruptedexception e) {e.printstacktrace ()}}} Class Threadtwo implements Runnable {private MyService myservice;public threadtwo (MyService myservice) {This.myservice = MyService;} @Overridepublic void Run () {try {myservice.updateb ();} catch (Interruptedexception e) {e.printstacktrace ()}}} Class MyService {private Object object;public MyService () {object = new object ();} public void UpdateA () throWS Interruptedexception {synchronized (object) {Long startTime = System.currenttimemillis (); System.out.println ("UpdateA startTime:" + startTime); Thread.Sleep (+); Long endTime = System.currenttimemillis (); System.out.println ("UpdateA endTime:" + EndTime);}} public void Updateb () throws Interruptedexception {synchronized (object) {Long startTime = System.currenttimemillis (); System.out.println ("Updateb startTime:" + startTime); Thread.Sleep (+); Long endTime = System.currenttimemillis (); System.out.println ("Updateb endTime:" + EndTime);}}}
Output:
UpdateA starttime:1462455786957
UpdateA endtime:1462455787958
Updateb starttime:1462455787958
Updateb endtime:1462455788958
2. Conclusion
From the output can be seen, compared to the previous section of the code, we put the synchronized () inside of a new object (), and this object is not necessarily object, can be any object
Summary: This chapter shows another use of the synchronized () code block, which can be used not only with this, but also with other objects.
This chapter is here, thank you.
------------------------------------------------------------------------------------
My github:https://github.com/raylee2015/deepintothread.
Catalog: http://blog.csdn.net/raylee2007/article/details/51204573
This chapter is here, thank you.
------------------------------------------------------------------------------------
My github:https://github.com/raylee2015/deepintothread.
Catalog: http://blog.csdn.net/raylee2007/article/details/51204573
Learn from the beginning multithreading -2.12 synchronized () code blocks can be used not only with this, but also with other objects