这里我有一个有 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());
}
}
最佳答案
拥有锁的第一个线程不会阻止第二个线程调用 Entity.print(String) 方法,因为该方法不会尝试获取锁。调用 print(String) 将 breakLoop 标志设置为 false。
(当标志值对另一个线程可见时,由于内存可见性问题而没有明确定义——最好使breakLoop实例变量成为 volatile 的——但这并不一定意味着第二个线程会永远不会看到实例变量的更改。内存可见性问题在某些平台上比其他平台上更明显。)
如果将 print(String) 方法更改为同步,它将挂起等待第一个线程完成。
关于java - 线程失去锁并给另一个线程执行的机会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292287/