Created
August 14, 2013 22:32
-
-
Save tigawa/6236331 to your computer and use it in GitHub Desktop.
Readロック、Writeロックを使ったサンプルです。
This file contains hidden or 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
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReentrantReadWriteLock; | |
public class TestReentrant implements Runnable { | |
Map<String, String> pool = new HashMap<String, String>(); | |
Lock lockObj; | |
/** | |
* メイン | |
* | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); | |
ExecutorService exec = Executors.newCachedThreadPool(); | |
exec.execute(new TestReentrant(lock.readLock())); | |
exec.execute(new TestReentrant(lock.readLock())); | |
exec.execute(new TestReentrant(lock.writeLock())); | |
exec.execute(new TestReentrant(lock.readLock())); | |
// new Thread(new TestReentrant(lock.readLock())).start(); | |
// new Thread(new TestReentrant(lock.readLock())).start(); | |
// new Thread(new TestReentrant(lock.writeLock())).start(); | |
// new Thread(new TestReentrant(lock.readLock())).start(); | |
} | |
/** | |
* コンストラクタ | |
* | |
* @param writeFlg | |
*/ | |
public TestReentrant(Lock lockObj) { | |
this.lockObj = lockObj; | |
} | |
public void task() throws InterruptedException { | |
String lockName = this.lockObj.getClass().getSimpleName(); | |
try { | |
this.lockObj.lock(); | |
System.out.printf("[%s] start\r\n", lockName); | |
Thread.sleep(3000L); | |
} finally { | |
System.out.printf("[%s] end\r\n", lockName); | |
this.lockObj.unlock(); | |
} | |
} | |
@Override | |
public void run() { | |
try { | |
task(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment