Ein paar alternative Lösungen für 10.4
parent
51328f56cb
commit
8577edd5e7
@ -0,0 +1,14 @@
|
||||
package _10._4.lukas;
|
||||
|
||||
public abstract class NameOutput {
|
||||
|
||||
private NameOutput() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int n = 3;
|
||||
for(int i = 0; i < n; i++) {
|
||||
new NameOutputFairLock().start();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package _10._4.lukas;
|
||||
|
||||
// ordered by creation time, deadlocks if any thread in the chain is interrupted.
|
||||
public class NameOutputBusyWaiting extends Thread {
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
private static int counter = 0;
|
||||
private static int total = 0;
|
||||
|
||||
private final int number;
|
||||
|
||||
public NameOutputBusyWaiting() {
|
||||
synchronized(LOCK) {
|
||||
this.number = total;
|
||||
total++;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while(!this.isInterrupted()) {
|
||||
synchronized(LOCK) {
|
||||
if(this.number == counter) {
|
||||
System.out.println(this.getName());
|
||||
counter = (counter + 1) % total;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
package _10._4.lukas;
|
||||
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
// ordered by least recent access since creation
|
||||
public class NameOutputFairLock extends Thread {
|
||||
|
||||
private static final Lock LOCK = new ReentrantLock(true);
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while(!this.isInterrupted()) {
|
||||
LOCK.lock();
|
||||
try {
|
||||
System.out.println(this.getName());
|
||||
} finally {
|
||||
LOCK.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package _10._4.lukas;
|
||||
|
||||
// ordered by creation time, deadlocks if any thread in the chain is interrupted.
|
||||
public class NameOutputWaitNotify extends Thread {
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
private static int counter = 0;
|
||||
private static int total = 0;
|
||||
|
||||
private final int number;
|
||||
|
||||
public NameOutputWaitNotify() {
|
||||
synchronized(LOCK) {
|
||||
this.number = total;
|
||||
total++;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while(!this.isInterrupted()) {
|
||||
synchronized(LOCK) {
|
||||
while(this.number != counter) {
|
||||
try {
|
||||
LOCK.wait();
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println(this.getName() + " was interrupted");
|
||||
}
|
||||
}
|
||||
System.out.println(this.getName());
|
||||
counter = (counter + 1) % total;
|
||||
LOCK.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue