美文网首页
2018-04-26

2018-04-26

作者: 萧然_fe14 | 来源:发表于2018-05-04 08:53 被阅读0次

关于线程锁的问题  

synchronized   是对当前对象加锁  所不同的地方是  synchronized 在不实用静态声明static 的时候对的是当前对象加锁 ,而加了静态声明的时候对的是当前的类 加锁    实现了同步   

Class A {

    public synchronized methodA() {//对当前对象加锁

    }

    public  methodB() {

synchronized(this){}//对当前对象加锁,与methodA用法相同

}

    public static synchronized methodC() {}//对类加锁,即对所有此类的对象加锁

    public methodD(){

synchronized(A.class){}//对类加锁,即对所有此类的对象加锁

}

}

如下例代码所示

public class MultiThread {

private  int count=0;

        public  synchronized void printOut(String tag)throws InterruptedException {

if(tag.equals("a")){

count=100;

                Thread.sleep(2000);

                System.out.println("tag="+tag+",count="+count);

            }else{

count=200;

                System.out.println("tag="+tag+",count="+count);

            }

}

public static void main(String args[]){

final MultiThread m1=new MultiThread();

            final MultiThread m2=new MultiThread();

            Thread t1=new Thread(new Runnable() {

public void run() {

try {

m1.printOut("a");

                    }catch (InterruptedException e) {

e.printStackTrace();

                    }

}

});

            Thread t2=new Thread(new Runnable() {

public void run() {

try {

m2.printOut("b");

                    }catch (InterruptedException e) {

e.printStackTrace();

                    }

}

});

            t1.start();

            t2.start();

        }

}

tag=b,count=200

tag=a,count=100

t1和t2 是同时执行的  synchronized 分别锁的是自身的那个实例化对象

当加了  static 的时候  

public class MultiThread {

private static int count=0;

        public static synchronized void printOut(String tag)throws InterruptedException {

if(tag.equals("a")){

count=100;

                Thread.sleep(2000);

                System.out.println("tag="+tag+",count="+count);

            }else{

count=200;

                System.out.println("tag="+tag+",count="+count);

            }

}

public static void main(String args[]){

final MultiThread m1=new MultiThread();

            final MultiThread m2=new MultiThread();

            Thread t1=new Thread(new Runnable() {

public void run() {

try {

m1.printOut("a");

                    }catch (InterruptedException e) {

e.printStackTrace();

                    }

}

});

            Thread t2=new Thread(new Runnable() {

public void run() {

try {

m2.printOut("b");

                    }catch (InterruptedException e) {

e.printStackTrace();

                    }

}

});

            t1.start();

            t2.start();

        }

}

tag=a,count=100

tag=b,count=200

锁住了当前的类    因为t1先执行所以获得类锁   之后t2必须等待t1执行完

run方法之后才能获得锁

相关文章

网友评论

      本文标题:2018-04-26

      本文链接:https://www.haomeiwen.com/subject/myoplftx.html