java - 如何让其他线程继续锁定for循环内的元素

假设我有以下代码


public class ContinueIfCannotLock implements Runnable

{


static List<LockingObject> lockObjects = new ArrayList();

@Override

   public void run()

   {

       for(LockingObject obj : lockObjects)

       {

           synchronized ( obj )

           {

            // do things here

           }

       }


   }


}

而 LockingObject 只是一个空类。还假设在这些线程开始之前,我们在 LockingObject 列表中有 100 个对象。那么,如果线程无法获取当前元素的锁,我该如何让线程继续访问列表中的下一个对象。这样就没有线程(至少在所有对象都没有被线程锁定之前)在循环内等待。


德玛西亚99
浏览 265回答 2
2回答

繁花不似锦

尝试使用Thread.holdsLock(Object obj),当且仅当当前线程持有指定对象的监视器锁时,才返回 true。~线程 (Java 平台 SE 8)&nbsp;~static List<LockingObject> lockObjects = new ArrayList();@Override&nbsp; &nbsp;public void run(){&nbsp; &nbsp; &nbsp; &nbsp;for(LockingObject obj : lockObjects){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(Thread.holdsLock(obj)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue; //continue the loop if object is locked.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;synchronized(obj){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// do things here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}}

富国沪深

您可以使用锁:static List<ReentrantLock> lockObjects;public static void init(){&nbsp; &nbsp;lockObjects = new ArrayList<>(100);&nbsp; &nbsp;for(int i = 0; i<100;i++){&nbsp; &nbsp; &nbsp; lockObjects.add(new ReentrantLock());&nbsp; &nbsp;}}@Overridepublic void run(){&nbsp; &nbsp; for(LockingObject lock : lockObjects)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(lock.tryLock()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;try{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //dostuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}finally{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;lock.unlock();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// break if you only want the thread to work once&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}如果您的唯一目标是让最多 100 个线程同时工作,您还可以使用 aSemaphore这是一个锁,让多个线程将其锁定到指定值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java