Я работаю над следующими кодами.
CreateThread. java
import java.util.concurrent.locks.*;
class CreateThread
{
public static void main(String[] args)
{
StampedLock lock = new StampedLock();
MyThread[] t = new MyThread[5];
for(int i=0; i<2; i++)
{
t[i] = new MyThread("t"+i, lock);
}
for(int i=0; i<2; i++)
{
t[i].start();
}
}
}
MyThread. java
import java.util.concurrent.locks.*;
public class MyThread extends Thread
{
StampedLock lock = null;
public MyThread(String name, StampedLock lock)
{
super(name);
this.lock=lock;
}
public void run()
{
long stamp = 0;
stamp = lock.tryOptimisticRead();
System.out.println(Thread.currentThread().getName()+" applied for Lock "+ stamp);
if(lock.validate(stamp))
{
System.out.println(Thread.currentThread().getName()+" got Lock "+ lock);
}
try
{
Thread.sleep(5000);
}
catch(InterruptedException e){}
lock.unlock(stamp);
}
}
Вывод:
t1 applied for Lock 256
t0 applied for Lock 256
t0 got Lock java.util.concurrent.locks.StampedLock@1ce4c0a1[Unlocked]
t1 got Lock java.util.concurrent.locks.StampedLock@1ce4c0a1[Unlocked]
Exception in thread "t0" java.lang.IllegalMonitorStateException
at java.base/java.util.concurrent.locks.StampedLock.unlockRead(StampedLock.java:722)
at java.base/java.util.concurrent.locks.StampedLock.unlock(StampedLock.java:738)
at MyThread.run(MyThread.java:24)
Exception in thread "t1" java.lang.IllegalMonitorStateException
at java.base/java.util.concurrent.locks.StampedLock.unlockRead(StampedLock.java:722)
at java.base/java.util.concurrent.locks.StampedLock.unlock(StampedLock.java:738)
at MyThread.run(MyThread.java:24)
Кажется, что оба потока никогда не блокировались на чтение. Как работает этот метод?