类级别锁与对象级别锁的概念,并带有多个示例

时间:2019-05-21 03:47:56

标签: java

在ObjectLevelLock上完成以下同步 那么行为将是什么?我们可以将其视为类级别锁吗?

public class ClassLevelLock implements Runnable {

    public void run() {
        Lock();
    }

    public void Lock() throws InterruptedException {
        System.out.println( "Lock() : before sync block Thread:" + Thread.currentThread().getName() );
        synchronized ( ObjectLevelLock.class ) { //Can this block work as a //class level lock or How it behaves?
            System.out.println( "Lock():  in block " + Thread.currentThread().getName() );
            Thread.sleep( 2000 );
            System.out.println( "Lock() : in block " + Thread.currentThread().getName() + " end" );
        }
    }
}

public class ObjectLevelLock implements Runnable {

    public void run() {
        Lock();
    }

    public void Lock() {
        System.out.println( Thread.currentThread().getName() );
        synchronized ( this ) {
            System.out.println( "in block " + Thread.currentThread().getName() );
            System.out.println( "in block " + Thread.currentThread().getName() + " end" );
        }
    }
}

在以下附加到ClassLevelLock而不是ObjectLevelLock的代码线程中。

public class Main {

    public static void main( final String[] args ) {
        new Main().callClassLevelLock();
    }
    public void callClassLevelLock() {
        ClassLevelLock g1 = new ClassLevelLock();
        Thread t1 = new Thread( g1 );
        Thread t2 = new Thread( g1 );
        ClassLevelLock g2 = new ClassLevelLock();
        Thread t3 = new Thread( g2 );
        Thread t4 = new Thread( g2 );
        Thread t5 = new Thread( g2 );
        t1.setName( "t1" );
        t2.setName( "t2" );
        t3.setName( "t3" );
        t4.setName( "t4" );
        t5.setName( "t5" );
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

0 个答案:

没有答案