来自: http://blog.csdn.net//never_cxb/article/details/50378571
锁住对象和该对象对应的类
看下面的代码
- class Sync {
- public void test() {
- synchronized (this) {
- System.out.println("test开始..");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("test结束..");
- }
- }
- }
- class MyThread extends Thread {
- private Sync s;
- MyThread(Sync s) {
- this.s = s;
- }
- public void run() {
- s.test();
- }
- }
- public class aa {
- public static void main(String[] args) {
- for (int i = 0; i < 3; i++) {
- Sync sync = new Sync();
- Thread thread = new MyThread(sync);
- thread.start();
- }
- }
- }
复制代码
注意我们在 main 里面的 for 循环每次都新建了一个新的 Sync 对象,如果是synchronized (this) ,锁同一个对象,但是源代码是多个对象,所以没有锁的效果。输出:
- test开始..
- test结束..
- test开始..
- test结束..
- test开始..
- test结束..
复制代码
如果把 main 函数改为如下:
- public static void main(String[] args) {
- Sync sync = new Sync();
- for (int i = 0; i < 3; i++) {
- Thread thread = new MyThread(sync);
- thread.start();
- }
- }
复制代码
我们新建 Sync 对象放在 for 循环之外,所以只有一个 Sync 对象,被 this 锁住,输出是加锁的效果
- test开始..
- test结束..
- test开始..
- test结束..
- test开始..
- test结束..
复制代码
如果我们想对于多个 Sync 对象都加锁,那么需要用 synchronized (Sync.class), 实现锁这个类对应的Class对象。
- public void test() {
- synchronized (Sync.class) {
- System.out.println("test开始..");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("test结束..");
- }
- }
复制代码
输出结果是加锁的效果:
- test开始..
- test结束..
- test开始..
- test结束..
- test开始..
- test结束..
复制代码
Java线程同步:synchronized锁住的是代码还是对象 |