How to block object from changing while executing thread

时间:2016-03-04 18:10:00

标签: java multithreading synchronization locking

i have a problem when I execute a thread. The problem occurs when i delete an object from the main thread while i was executing another thread that updates that object. By the moment the second thread tries to update the object, and Exception occurs as the object no longer exists. My question is the following: How can i block other threads from modifying my object while I'm running my special thread? I want my special thread to have priority over every other thread in the application.

Thank you very much

1 个答案:

答案 0 :(得分:-1)

有多种方法可以实现这一目标:

(a)使用锁定或同步(在对象上使用同步块)方式同步删除和对象访问调用

(b)编辑:使用初始值为1的原子整数。删除时将其标记为0,并在修改时将其标记为-1(完成时重新标记为1),修改线程将检查if (atomicCounter != 0)在继续修改对象之前,删除线程将在删除之前检查while (atomicCounter != -1)(即等待变为零)

(c)使用与倒计时锁存器相反的东西(计数锁存器,它在Java库中不存在)

(d)不要做任何事情,如果发生异常,使用catch正确处理它,最后阻止并让线程代码继续按你希望的那样