这一章节我们来讨论一下同步方法与同步静态代码块持有的是不同的锁。
代码清单:
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 { @Override public void run() { try { MyService.updateA(); } catch (InterruptedException e) { e.printStackTrace(); } } } class ThreadTwo implements Runnable { private MyService myService; public ThreadTwo(MyService myService) { this.myService = myService; } @Override public 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); } } }
输出:
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
从输出可以看见,两个线程的输出是不同步的,从而证明两个方法持有的是不同的锁。
总结:这一章节主要展示了同步方法与同步静态代码块持有的是不同的锁。
这一章节就到这里,谢谢
------------------------------------------------------------------------------------
我的github:https://github.com/raylee2015/DeepIntoThread
目录:http://blog.csdn.net/raylee2007/article/details/51204573
时间: 2024-11-05 17:22:31