This commit is contained in:
Luca Conte 2025-04-23 23:17:29 +02:00
parent 2640d71549
commit 8bb915ce5c
3 changed files with 82 additions and 0 deletions

26
u06-5/Concurrent.java Normal file
View File

@ -0,0 +1,26 @@
abstract class Concurrent<ArgType> {
private ArgType[] args;
public Concurrent(ArgType[] args) {
this.args = args;
}
void run() {
Thread[] threads = new Thread[args.length];
for (int i = 0; i < args.length; i++) {
final ArgType arg = args[i];
threads[i] = new Thread(() -> perform(arg));
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
abstract void perform(ArgType arg);
}

20
u06-5/SpinLock.java Normal file
View File

@ -0,0 +1,20 @@
import java.util.concurrent.atomic.AtomicReference;
class SpinLock {
private AtomicReference<Thread> currentThread;
public SpinLock() {
currentThread = new AtomicReference<Thread>(null);
}
public void lock() {
Thread thisThread = Thread.currentThread();
// wait for currentThread to be null to acquire lock
while (!currentThread.compareAndSet(null, thisThread));
}
public boolean unlock() {
return currentThread.compareAndSet(Thread.currentThread(), null);
}
}

36
u06-5/SpinLockTest.java Normal file
View File

@ -0,0 +1,36 @@
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();
}
}