我是java中的多线程新手。我试图使用locks.Here是我的代码示例。
package com;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class UsingLocks {
Lock lock = new ReentrantLock();
public static void main(String[] args) {
// TODO Auto-generated method stub
UsingLocks job = new UsingLocks();
Thread [] threads= new Thread[5];
for(int i=0;i<5;i++){
threads[i]= new Thread(new LockTask(job));
}
for(int i=0;i<5;i++){
threads[i].start();
}
}
public void lockingJob() {
System.out.println("Thread "+Thread.currentThread().getName()+" trying to Acquire lock");
try {
lock.tryLock();
//lock.lock(); //When I use this, code works fine
int time=new Random().nextInt(10)+3;
System.out.println("Thread "+Thread.currentThread().getName()+" Acquired lock for "+time+" seconds.");
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Now releasing lock "+Thread.currentThread().getName());
lock.unlock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("After Unlock "+Thread.currentThread().getName());
}
}
class LockTask implements Runnable{
UsingLocks job;
public LockTask(UsingLocks job) {
// TODO Auto-generated constructor stub
this.job=job;
}
@Override
public void run() {
// TODO Auto-generated method stub
job.lockingJob();
}
}
以下是我使用tryLock()
时的输出Thread Thread-1 trying to Acquire lock
Thread Thread-0 trying to Acquire lock
Thread Thread-2 trying to Acquire lock
Thread Thread-1 Acquired lock for 12 seconds.
Thread Thread-2 Acquired lock for 3 seconds.
Thread Thread-0 Acquired lock for 8 seconds.
Thread Thread-3 trying to Acquire lock
Thread Thread-3 Acquired lock for 9 seconds.
Thread Thread-4 trying to Acquire lock
Thread Thread-4 Acquired lock for 6 seconds.
Now releasing lock Thread-2
Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:155)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1260)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:460)
at com.UsingLocks.lockingJob(UsingLocks.java:37)
at com.LockTask.run(UsingLocks.java:66)
at java.lang.Thread.run(Thread.java:745)
Now releasing lock Thread-4
Exception in thread "Thread-4" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:155)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1260)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:460)
at com.UsingLocks.lockingJob(UsingLocks.java:37)
at com.LockTask.run(UsingLocks.java:66)
at java.lang.Thread.run(Thread.java:745)
现在,按照我的理解,当第一个线程执行tryLock()时,它应该获取锁,而其他线程应该无法获取lock.But如输出中所示。在Thread-1获取锁之后,Thread -2还获得了锁定等。这怎么可能。请告诉我这里缺少什么。 提前致谢。
答案 0 :(得分:0)
ReentrantLock#tryLock()
- 只有在调用时没有被另一个线程持有时才获取锁。如果成功,则返回true。
如果我们看到堆栈跟踪 -
...
Now releasing lock Thread-2
Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
...
Now releasing lock Thread-4
Exception in thread "Thread-4" java.lang.IllegalMonitorStateException
...
更清楚的是,无法获取锁定的线程,在尝试释放它时引发异常。
答案 1 :(得分:0)
我稍微修改了你的代码并为自己试了一下。
我发现无论我做什么,ReentrantLock.tryLock都会抛出IllegalMonitorStateException。我不认为这是合适的。
package concurrency;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* LockableTask is a nice demonstration
* @author Michael
* @link https://stackoverflow.com/questions/32680954/reetrant-locks-in-java
* @since 9/20/2015 11:25 AM
*/
public class LockableTask implements Runnable {
private static final int DEFAULT_WAIT = 100;
private static final int DEFAULT_TIMEOUT = 1000;
private static final int DEFAULT_THREADS = 5;
private ReentrantLock lock;
private int waitPeriod;
private int timeoutPeriod;
private boolean halfHeartedLockRequest;
public static void main(String[] args) {
long begTime = System.currentTimeMillis();
System.out.println("Start reentrant lock test");
try {
LockableTask lockableTask = new LockableTask(true, false);
int numThreads = (args.length > 0) ? Integer.parseInt(args[0]) : DEFAULT_THREADS;
List<Thread> threads = new ArrayList<>(numThreads);
for (int i = 0; i < numThreads; ++i) {
threads.add(new Thread(lockableTask));
}
for (Thread thread : threads) {
thread.start();
}
} finally {
long endTime = System.currentTimeMillis();
System.out.println(String.format("Complete reentrant lock test in %d milliseconds", (endTime-begTime)));
}
}
public LockableTask() {
this(false, false, DEFAULT_WAIT, DEFAULT_TIMEOUT);
}
public LockableTask(boolean halfHeartedLockRequest, boolean fair) {
this(halfHeartedLockRequest, fair, DEFAULT_WAIT, DEFAULT_TIMEOUT);
}
public LockableTask(boolean halfHeartedLockRequest, boolean fair, int waitPeriod, int timeoutPeriod) {
this.halfHeartedLockRequest = halfHeartedLockRequest;
this.lock = new ReentrantLock(fair);
this.waitPeriod = (waitPeriod > 0) ? waitPeriod : DEFAULT_WAIT;
this.timeoutPeriod = (timeoutPeriod > 0) ? timeoutPeriod : DEFAULT_TIMEOUT;
}
@Override
public void run() {
System.out.println(String.format("Thread '%s' requests lock ", Thread.currentThread().getName()));
if (this.halfHeartedLockRequest) {
this.lock.tryLock();
} else {
this.lock.lock();
}
try {
System.out.println(String.format("Thread '%s' acquires lock for %d ", Thread.currentThread().getName(), this.waitPeriod));
TimeUnit.MILLISECONDS.sleep(this.waitPeriod);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
this.lock.unlock();
System.out.println(String.format("Thread '%s' releases lock ", Thread.currentThread().getName()));
}
}
}
答案 2 :(得分:0)
对tryLock()的调用仅返回一个布尔值,它对是否执行(如果有)下的“无关联” ,或者不。 这就是为什么将tryLock()用作检查要同步的某些活动/代码块的原因。希望能回答您的问题。