Reputation: 11768
I have some runnable code that is executed through a thread.The thread is executed by multiple pieces of code how can I make sure there is only one thread that executes that runnable at a certain point.
I tried using a boolean value that is true on thread start and becomes false at thread end but that didn't help.
Any ideas?
Upvotes: 2
Views: 3539
Reputation: 7458
private class MyThread extends Thread
{
private static Lock lock = new ReentrantLock();
public void run()
{
if (MyThread.lock.tryLock())
{
try
{
// TODO something
}
finally
{
MyThread.lock.unlock();
}
}
}
}
Upvotes: 2
Reputation: 33534
- First of all its the resources of an object that multiple threads access.
- Now if you want to let only 1 thread access that resource at an instance of time, then you can do the followings*:*
1. Use java.util.concurrent.Semaphore
with number of thread equals 1, so only 1 thread at an time instance can access that resource.
Eg:
Semaphore s = new Semaphore(1);
2. You can also use SingleThreadExecutor
, as it completes one task before going on the the second on and and so on. So there is No need of using synchronization.
Upvotes: 3