「Java入門」マルチスレッドで排他制御Lockの使い方

Javaコード:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
public static void main(String[] args) {
final Ljout output = new Ljout();
new Thread() {
public void run() {
output.output(“thread1 is running");
};
}.start();
new Thread() {
public void run() {
output.output(“thread2 is running");
};
}.start();
}

}
class Ljout {
private Lock lockObj = new ReentrantLock();
public void output(String name) {
lockObj.lock();
try {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
System.out.println(“\n");
} finally {
lockObj.unlock();
}
}
}
実行結果:
thread1 is running

thread2 is running

Java

Posted by arkgame