Compare commits

..

10 Commits

Author SHA1 Message Date
Shahnam Javidnia 28611e3e2f Random
signal
constructor
2025-05-04 21:48:06 +02:00
Shahnam Javidnia 82f41974d1 dont need comment anymore
adding volatile
2025-05-03 20:56:09 +02:00
Shahnam Javidnia bcb6d6f045 Merge remote-tracking branch 'origin/Test-SJ' into Test-SJ
# Conflicts:
#	pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java
2025-05-03 20:31:39 +02:00
Shahnam Javidnia 29c257adea final 2025-05-03 20:31:10 +02:00
Shahnam Javidnia 5761ad257a Update pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java 2025-05-03 16:16:55 +02:00
Shahnam Javidnia 26ec95c75b Merge remote-tracking branch 'origin/Test-SJ' into Test-SJ
# Conflicts:
#	pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java
2025-05-03 16:14:19 +02:00
Shahnam Javidnia 8291fbed75 V1.1
(cast Philosopher)
2025-05-03 16:12:25 +02:00
Shahnam Javidnia c53e2b09ee Update pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java 2025-05-01 15:56:46 +02:00
Shahnam Javidnia 7723b7fb35 V1.0 2025-05-01 15:54:08 +02:00
Shahnam Javidnia 0fc6dd421f test 2025-05-01 14:10:09 +02:00
7 changed files with 80 additions and 393 deletions

View File

@ -18,6 +18,10 @@ public interface IPhilosopher {
void stopPhilosopher();
default void log(int seat, String message) {
synchronized (Philosopher.class) {
for (var i = 1; i <= seat; i++) {

View File

@ -1,18 +1,19 @@
package pp;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import static pp.PhilosopherExperiment.*;
import java.util.Random;
public class Philosopher extends Thread implements IPhilosopher {
private int seat;
private Philosopher rechts;
private Philosopher links;
private Philosopher left;
private Philosopher right;
private Lock table;
private Condition canEat;
private volatile boolean stopped;
private volatile boolean eating;
private volatile boolean eating = false;
private volatile boolean stopped = false;
private final Random random;
public Philosopher() {
@ -20,67 +21,21 @@ public class Philosopher extends Thread implements IPhilosopher {
this.seat = 0;
this.stopped = false;
}
@Override
public void run() {
try {
while (!this.stopped) {
think();
eat();
}
} catch (InterruptedException e) {
}
log(seat,"beendet");
}
private void eat() throws InterruptedException {
this.table.lock();
try {
while (this.links.eating || this.rechts.eating) {
log(seat,"warten!");
this.canEat.await();
}
this.eating = true;
log(seat, " : isst gerade!");
} finally {
table.unlock();
}
Thread.sleep(this.random.nextInt(PhilosopherExperiment.MAX_EATING_DURATION_MS));
}
private void think() throws InterruptedException {
this.table.lock();
try {
if (this.eating)
this.eating = false;
this.links.canEat.signal();
this.rechts.canEat.signal();
log(seat,"denken");
} finally {
this.table.unlock();
}
Thread.sleep(random.nextInt(PhilosopherExperiment.MAX_THINKING_DURATION_MS));
}
@Override
public void setLeft(IPhilosopher left) {
// TODO Auto-generated method stub
// Cast auf Philosopher erforderlich
this.links = (Philosopher) left;
if (left == null) throw new IllegalArgumentException("Left philosopher must not be null.");
this.left = (Philosopher) left;
}
@Override
public void setRight(IPhilosopher right) {
// TODO Auto-generated method stub
// Cast auf Philosopher erforderlich
this.rechts = (Philosopher) right;
if (right == null) throw new IllegalArgumentException("Right philosopher must not be null.");
this.right = (Philosopher) right;
}
@Override
@ -91,48 +46,77 @@ public class Philosopher extends Thread implements IPhilosopher {
@Override
public void setTable(Lock table) {
// TODO Auto-generated method stub
this.table = table;
canEat = this.table.newCondition();
this.canEat = table.newCondition();
}
@Override
public void stopPhilosopher() {
// TODO Auto-generated method stub
this.stopped = true;
interrupt();
this.interrupt();
}
public static void main(String[] args) throws InterruptedException {
int numPhilosophers = 5;
Lock table = new ReentrantLock();
Philosopher[] philosophers = new Philosopher[numPhilosophers];
for (int i = 0; i < numPhilosophers; i++) {
philosophers[i] = new Philosopher();
philosophers[i].setSeat(i);
philosophers[i].setTable(table);
}
for (int i = 0; i < numPhilosophers; i++) {
philosophers[i].setLeft(philosophers[(i + numPhilosophers - 1) % numPhilosophers]);
philosophers[i].setRight(philosophers[(i + 1) % numPhilosophers]);
}
for (Philosopher p : philosophers) {
p.start();
}
Thread.sleep(10_000); // Laufzeit: 10 Sekunden
for (Philosopher p : philosophers) {
p.stopPhilosopher();
}
for (Philosopher p : philosophers) {
p.join();
}
System.out.println("Experiment beendet!");
public void run() {
try {
while (!stopped) {
think();
beginEating();
eat();
endEating();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void endEating() {
table.lock();
try {
eating = false;
log(seat, "hat fertig gegessen");
left.canEat.signal();
right.canEat.signal();
} finally {
table.unlock();
}
}
private void eat() throws InterruptedException {
Thread.sleep(random.nextInt(MAX_EATING_DURATION_MS));
}
private void beginEating() throws InterruptedException {
table.lock();
try {
while (left.eating || right.eating) {
log(seat, "wartet");
canEat.await();
}
eating = true;
log(seat, "isst jetzt");
} finally {
table.unlock();
}
}
private void think() throws InterruptedException {
log(seat, "denkt");
Thread.sleep(random.nextInt(MAX_THINKING_DURATION_MS));
table.lock();
try {
left.canEat.signal();
right.canEat.signal();
} finally {
table.unlock();
}
}
}

View File

@ -1,3 +0,0 @@
/target/
/.classpath
/.project

View File

@ -1,62 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pp</groupId>
<artifactId>pp.A4-HandOverHandLocking</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<exec.mainClass>pp.Main</exec.mainClass>
<maven.compiler.release>10</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency><!-- für Unit-Tests -->
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency><!-- für Lombok -->
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
<dependency><!-- für net.jcip Annotationen -->
<groupId>net.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>clean compile exec:java</defaultGoal>
<plugins>
<plugin><!-- für Unit-Tests [mvn test] -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin><!-- [mvn compile] -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.9.0</version>
</plugin>
<plugin><!-- [mvn exec:java] -->
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin><!-- [mvn javadoc:javadoc] -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<show>private</show>
<locale>en_US</locale>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,43 +0,0 @@
package pp;
public class Main {
static SimplifiedList<Integer> list;
static Runnable sliceSum(int start, int end, int expected) {
return () -> {
var sum = 0;
for (var i = start; i < end; i++) {
sum += list.get(i);
}
if (sum != expected) {
System.out.println("Fehler in "
+ Thread.currentThread().getName() + ": " + sum);
}else
System.out.println("Kein Fehler in " + Thread.currentThread().getName() + ": " + sum);
};
}
public static void main(String... args) throws InterruptedException {
list = new ThreadsafeSimplifiedList<>();
for (int i = 0; i < 5000; i++) {
list.add(i);
}
var thread0 = new Thread(sliceSum(0, 1250, 780625));
var thread1 = new Thread(sliceSum(1250, 2500, 2343125));
var thread2 = new Thread(sliceSum(2500, 3750, 3905625));
var thread3 = new Thread(sliceSum(3750, 5000, 5468125));
var start = System.currentTimeMillis();
thread0.start();
thread1.start();
thread2.start();
thread3.start();
thread0.join();
thread1.join();
thread2.join();
thread3.join();
System.out.printf("%s: %d ms\n", list.getClass().toString(),
System.currentTimeMillis() - start);
}
}

View File

@ -1,58 +0,0 @@
package pp;
public interface SimplifiedList<T> {
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws Exception
*/
public T get(int index);
/**
* Appends the specified element to the end of this list. There are no
* limitations on what elements may be added to this list.
*
* @param element element to be appended to this list
* @return true
* @see java.util.Collection#add(Object)
*
*/
public boolean add(T element);
/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws Exception
*/
public T set(int index, T element);
/**
* Returns true if this list contains no elements.
*
* @return true if this list contains no elements
*/
public boolean isEmpty();
/**
* delayed passing through of parameter
*
* @param element element to pass through
* @return passed though element
*
*/
public default T delay(T element) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
return element;
}
}

View File

@ -1,135 +0,0 @@
package pp;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadsafeSimplifiedList<T>
implements SimplifiedList<T> {
private Node<T> head;
private final Lock listLock = new ReentrantLock();
private class Node<U> {
private U element;
private Node<U> next;
private final Lock nodeLock;
private Node(U element, Node<U> prev, Node<U> next) {
super();
this.element = element;
this.next = next;
this.nodeLock = new ReentrantLock();
}
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
*/
@Override
public T get(int index){
this.listLock.lock();
if (this.head == null) {
this.listLock.unlock();
throw new IndexOutOfBoundsException("The list is empty");
}
var ptr = this.head;
ptr.nodeLock.lock();
this.listLock.unlock();
for (var i = 0; i < index; i++) {
if (ptr.next != null) {
ptr.next.nodeLock.lock();
var savePtr = ptr;
ptr = ptr.next;
savePtr.nodeLock.unlock();
} else {
throw new IndexOutOfBoundsException(index + " out of bounds");
}
}
try {return delay(ptr.element);}
finally { ptr.nodeLock.unlock();}
}
/**
* Appends the specified element to the end of this list. There are no
* limitations on what elements may be added to this list.
*
* @param element element to be appended to this list
* @return true
* @see java.util.Collection#add(Object)
*
*/
@Override
public boolean add(T element) {
this.listLock.lock();
if (this.head != null) {
var ptr = this.head;
ptr.nodeLock.lock();
this.listLock.unlock();
while (ptr.next != null) {
ptr.next.nodeLock.lock();
var savePtr = ptr;
ptr = ptr.next;
savePtr.nodeLock.unlock();
}
ptr.next = new Node<>(element, ptr, null);
ptr.nodeLock.unlock();
} else {
this.head = new Node<>(element, null, null);
this.listLock.unlock();
}
return true;
}
/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
*/
@Override
public T set(int index, T element) {
this.listLock.lock();
if (this.head == null) {
this.listLock.unlock();
throw new IndexOutOfBoundsException("The list is empty");
}
var ptr = this.head;
ptr.nodeLock.lock();
this.listLock.unlock();
for (var i = 0; i < index; i++) {
if (ptr.next != null) {
ptr.next.nodeLock.lock();
var savePtr = ptr;
ptr = ptr.next;
savePtr.nodeLock.unlock();
} else
throw new IndexOutOfBoundsException(index + " out of bounds");
}
try {
ptr.element = element;
return element;
} finally {
ptr.nodeLock.unlock();
}
}
/**
* Returns true if this list contains no elements.
*
* @return true if this list contains no elements
*/
@Override
public boolean isEmpty() {
this.listLock.lock();
try { return this.head == null; }
finally { this.listLock.unlock();}
}
}