In this chapter we discuss the synchronization method and the synchronous static block of code that hold different locks.
Code Listing:
Package com.ray.deepintothread.ch02.topic_18;/** * * @author Raylee * */public class Synchclass {public static void main ( String[] args) throws Interruptedexception {MyService myservice = new MyService (); Threadone Threadone = new Threadone (); Thread thread = new Thread (threadone); Thread.Start (); Threadtwo threadtwo = new Threadtwo (MyService); Thread thread2 = new Thread (threadtwo); Thread2.start ();}} Class Threadone implements Runnable {@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 static int id = 0;public synchronized static void UpdateA () throws interruptedexception {for (int i = 0; I < 5; i++) {System.out.println (Thread.CurrentThread (). GetName () + "" + id++);Thread.Sleep (50);}} Public synchronized void Updateb () throws interruptedexception {for (int i = 0; i < 5; i++) {System.out.println (Thread. CurrentThread (). GetName () + "" + id++); Thread.Sleep (100);}}
Output:
Thread-0 0
Thread-1 1
Thread-0 2
Thread-1 3
Thread-0 4
Thread-0 5
Thread-0 6
Thread-1 7
Thread-1 8
Thread-1 9
As you can see from the output, the output of two threads is out of sync, proving that two methods hold different locks.
Summary: This chapter mainly shows that the synchronization method and the synchronous static code block hold different locks.
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 multi-threading-2.17 synchronous methods and synchronous static code blocks hold different locks