Created
September 3, 2012 06:11
-
-
Save daichan4649/3607174 to your computer and use it in GitHub Desktop.
ReentrantLock test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
lock中は別スレからlock不可
別スレでlock(read/write)中の lock取得(read/write) は可能。
ただ、lock解放はlock時と同じスレッドで行う必要あり。
別スレで解放すると以下の例外発生。
java.lang.IllegalMonitorStateException:
attempt to unlock read lock, not locked by current thread