Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1039108
  • 博文数量: 155
  • 博客积分: 5339
  • 博客等级: 大校
  • 技术积分: 1436
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-10 21:41
文章分类

全部博文(155)

文章存档

2016年(3)

2015年(7)

2014年(3)

2013年(1)

2012年(8)

2011年(5)

2010年(1)

2009年(5)

2008年(4)

2007年(26)

2006年(46)

2005年(46)

分类: Java

2005-08-22 15:44:19

把近几天解决的几个同步问题记录一下

同步锁分为两种:类锁和对象锁。

使用类锁最直接的用法:synchronized(StaticObj.class){...}

同样使用类锁的还有同步静态方法:public synchronized static void sprint(int n){...}

所有使用同一个类的类锁的方法和同步块只有一个能够执行,其他将被阻塞。

有意思的是,对象锁与类锁刚好有一个对应方法块和一个方法:

synchronized(this){...}

public synchronized void syncprint(int n){...}

对象锁只针对某个特定的实例对象,锁的范围要小很多,下面是一个用来验证的例子,类锁和对象锁都能得到验证

public class StaticObj {

//类锁
    public void print(int n){
        synchronized(StaticObj.class){
            for(int i=0;i<50;i++)
            System.out.println("####"+n);

        }
    }
    //对象锁
    public synchronized void syncprint(int n){

            for(int i=0;i<50;i++)
            {
                System.out.println("####"+n);
            }

    }
    //对象锁
    public void tprint(int n){
         synchronized(this){
            for(int i=0;i<50;i++)
            {
                System.out.println("####"+n);

            }
         }
    }
    //类锁
    public synchronized static void sprint(int n){

            for(int i=0;i<50;i++)
            {
                System.out.println("####"+n);

            }

    }
}

//验证类

public class Foo extends Thread
{
     private int val;
     private StaticObj o;
     public Foo(int v,StaticObj so)
     {
        val = v;
        o=so;
     }
     public void printVal(int v)
     {
        StaticObj.sprint(v);
     }
     public void run()
     {
      printVal(val);
     }

    public static void main(String args[]){
        StaticObj so=new StaticObj();
        for(int i=0;i<10;i++){
            new Foo(i,so).start();
        }
    }
}

阅读(1553) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~