线程失去锁定并为另一个线程提供执行机会

时间:2014-08-13 17:14:58

标签: java multithreading

这里我有一个带有2个线程的对象,并通过print()提供对象的锁定,但是在一些循环之后它失去锁定并执行第二个线程,它将改变breakLoop的值,第一个线程将终止。

public class ThreadLock {
    public static void main(String[] args) {
        Entity entity=new Entity();
        RunnableClass runnable = new RunnableClass(entity);
        Thread threadClass= new Thread(runnable);
        Thread threadClass2= new Thread(runnable);
        threadClass.setName("First Thread");
        threadClass2.setName("Second Thread");
        threadClass.start();        
        threadClass2.start();
    }
}

class RunnableClass implements Runnable{
    Entity entity;
    public RunnableClass(Entity entity) {
        this.entity=entity;
    }
    public void run(){
        if(Thread.currentThread().getName().equalsIgnoreCase("First Thread"))
            entity.print();
        else{
            entity.print("");
        }
    }
}
class Entity{
    public void print(String str){
        System.out.println("Non sysncronized method accessed by  "+Thread.currentThread().getName());
        breakLoop=false;
    }
    boolean breakLoop=true;
    //lock will work for same object 
    public synchronized void print(){
        System.out.println("Lock aquired by : "+Thread.currentThread().getName());
        while (breakLoop) {
            System.out.println("hhhhhhhhhhhhhh");
        }
        System.out.println("Lock released by : "+Thread.currentThread().getName());
    }
}

1 个答案:

答案 0 :(得分:2)

具有锁定的第一个线程不会阻止第二个线程调用Entity.print(String)方法,因为该方法不会尝试获取锁定。调用print(String)将breakLoop标志设置为false。

(当由于内存可见性问题而导致另一个线程的标志值变得不明确时 - 将breakLoop实例变量设置为volatile会更好 - 但这并不一定意味着第二个线程会永远不会看到对实例变量的更改。内存可见性问题在某些平台上比其他平台更明显。)

如果更改要同步的print(String)方法,它将等待第一个线程完成。