码迷,mamicode.com
首页 > 编程语言 > 详细

从头认识多线程-2.17 同步方法与同步静态代码块持有的是不同的锁

时间:2016-05-12 11:30:40      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

这一章节我们来讨论一下同步方法与同步静态代码块持有的是不同的锁。

代码清单:

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


从头认识多线程-2.17 同步方法与同步静态代码块持有的是不同的锁

标签:

原文地址:http://blog.csdn.net/raylee2007/article/details/51376844

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!