37 lines
1.0 KiB
Java
37 lines
1.0 KiB
Java
class SpinLockTest extends Concurrent<SpinLock> {
|
|
|
|
SpinLockTest(SpinLock[] args) {
|
|
super(args);
|
|
}
|
|
protected void perform(SpinLock lock) {
|
|
System.out.println(Thread.currentThread().getName() +
|
|
" wartet auf das Lock...");
|
|
lock.lock();
|
|
|
|
System.out.println(Thread.currentThread().getName() +
|
|
" hat das Lock und behält es für etwa 1 Sek....");
|
|
try {
|
|
Thread.sleep((long) (500 + Math.random()*1000));
|
|
} catch (InterruptedException e) {
|
|
// Beim Schlafen zufaelliger Dauer unterbrochen zu werden ist kein Schaden
|
|
}
|
|
|
|
if (lock.unlock()) {
|
|
System.out.println(Thread.currentThread().getName() +
|
|
" hat das von ihm vorher gesperrte Lock freigegeben und endet.");
|
|
} else {
|
|
System.out.println(Thread.currentThread().getName() +
|
|
" hat das Lock schon freigegeben vorgefunden!?");
|
|
}
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
SpinLock sl = new SpinLock();
|
|
SpinLock[] locks = {sl, sl, sl, sl, sl};
|
|
// alle Threads benutzen dasselbe SpinLock sl
|
|
new SpinLockTest(locks).run();
|
|
}
|
|
}
|
|
|