u06-5
This commit is contained in:
parent
2640d71549
commit
8bb915ce5c
|
@ -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);
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue