类锁,对象锁

原创
2018/09/18 16:02
阅读数 87
/**
 * mark_
 * 1: 类锁,对象锁
 * 2: 对象锁:实例的实例同步方法只能被同一个线程进入;(类的同步方法也是如此)
 **/
public class ObjectLockMdTest {

    public synchronized void m1() throws Exception {
        System.err.println("m1:enter");
        while (true) {
            Thread.sleep(10000);//10秒
            break;
        }
        System.err.println("m1:end");
    }

    public synchronized void m2() {
        System.err.println("m2");
    }

    public static synchronized void m3() throws Exception {
        System.err.println("m3:enter");
        while (true) {
            Thread.sleep(10000);//10秒
            break;
        }
        System.err.println("m3:end");
    }

    public static synchronized void m4() {
        System.err.println("m4");
    }


    public static void testObjectLock() {
        ObjectLockMdTest test = new ObjectLockMdTest();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    test.m1();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                test.m2();
            }
        });

        t1.start();
        t2.start();
    }

    public static void testClassLock() {
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ObjectLockMdTest.m3();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t4 = new Thread(new Runnable() {
            @Override
            public void run() {
                ObjectLockMdTest.m4();
            }
        });

        t3.start();
        t4.start();
    }

    public static void main(String[] args) throws Exception {
       // testObjectLock();
        testClassLock();
    }

}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部