多线程基础学习第二篇(多个线程多把锁)

来源:互联网 发布:列表是什么网络意思 编辑:程序博客网 时间:2024/06/13 09:09

多个线程同时竞争多把锁(这是对象上的锁,因为每个对象都有一把锁,所以彼此之间不存在关系)

/** * @version V1.0 * @Description: 多个线程同时竞争多把锁 * 在静态方法上加synchronize关键字,表示锁定.class类,类一级别的锁(独占.class类) * @Modified By:Ming Created in  14:39 2017/3/22 */public class MyThread1 {    private  int num = 0;    /**     * static     **/    public  synchronized void printNum(String tag) {        try {            if (tag.equals("a")) {                num = 100;                System.out.println("tag a, set num over!" );                Thread.sleep(1000);            } else {                num = 200;                System.out.println("tag b, set num over!");            }            System.out.println("tag " + tag + ", set num over!" + num);        } catch (InterruptedException e) {            e.printStackTrace();        }    }    //注意观察run方法的输出顺序    public static void main(String[] args) {        //俩个不同的对象        final MyThread1 m1 = new MyThread1();        final MyThread1 m2 = new MyThread1();        Thread t1 = new Thread(new Runnable() {            public void run() {                m1.printNum("a");            }        });        Thread t2 = new Thread(new Runnable() {            public void run() {                m2.printNum("b");            }        });        t1.start();        t2.start();    }}tag a, set num over!tag b, set num over!tag b, set num over!200tag a, set num over!100

关键字synchronized取得的锁都是对象锁,而不是把一段代码(方法)当作锁,所以示例中的哪个线程先执行synchronized关键字的方法,哪个线程就持有该方法所属对象的锁(lock),如果是多个线程,那么线程获得的就是多个不同的锁,他们互不影响(但是有一种情况是相同的锁,即在静态方法上添加synchronized关键字,表示锁定.class,类一级别的锁,独占.class类)

(如果想要他们去竞争同一把锁的)加上静态修饰,变对象锁为类级别的锁

/** * @version V1.0 * @Description: 多个线程同时竞争多把锁 * 在静态方法上加synchronize关键字,表示锁定.class类,类一级别的锁(独占.class类) * @Modified By:Ming Created in  14:39 2017/3/22 */public class MyThread1 {    private static int num = 0;    /**     * static     **/    public static synchronized void printNum(String tag) {        try {            if (tag.equals("a")) {                num = 100;                System.out.println("tag a, set num over!" );                Thread.sleep(1000);            } else {                num = 200;                System.out.println("tag b, set num over!");            }            System.out.println("tag " + tag + ", set num over!" + num);        } catch (InterruptedException e) {            e.printStackTrace();        }    }    //注意观察run方法的输出顺序    public static void main(String[] args) {        //俩个不同的对象        final MyThread1 m1 = new MyThread1();        final MyThread1 m2 = new MyThread1();        Thread t1 = new Thread(new Runnable() {            public void run() {                m1.printNum("a");            }        });        Thread t2 = new Thread(new Runnable() {            public void run() {                m2.printNum("b");            }        });        t1.start();        t2.start();    }}tag b, set num over!tag b, set num over!200tag a, set num over!tag a, set num over!100
0 0
原创粉丝点击