Skip to content

Instantly share code, notes, and snippets.

@daichan4649
Created September 3, 2012 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daichan4649/3607174 to your computer and use it in GitHub Desktop.
Save daichan4649/3607174 to your computer and use it in GitHub Desktop.
ReentrantLock test
private void test() {
final LockTest test = new LockTest();
new Thread(new Runnable() {
@Override
public void run() {
test.lockTest();
// test.readLockTest();
// test.writeLockTest();
}
}, "AAA").start();
new Thread(new Runnable() {
@Override
public void run() {
test.lockTest();
// test.readLockTest();
// test.writeLockTest();
}
}, "BBB").start();
}
class LockTest {
private ReentrantLock lock = new ReentrantLock();
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
public void lockTest() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " start");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " end");
} catch (Exception e) {
} finally {
lock.unlock();
}
}
public void readLockTest() {
rwLock.readLock();
try {
System.out.println(Thread.currentThread().getName() + " start");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " end");
} catch (Exception e) {
} finally {
rwLock.readLock().unlock();
}
}
public void writeLockTest() {
rwLock.writeLock();
try {
System.out.println(Thread.currentThread().getName() + " start");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " end");
} catch (Exception e) {
} finally {
rwLock.writeLock().unlock();
}
}
}
@daichan4649
Copy link
Author

  • ReentrantLock
    lock中は別スレからlock不可
  • ReentrantReadWriteLock
    別スレでlock(read/write)中の lock取得(read/write) は可能。
    ただ、lock解放はlock時と同じスレッドで行う必要あり。
    別スレで解放すると以下の例外発生。

java.lang.IllegalMonitorStateException:
attempt to unlock read lock, not locked by current thread

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment