Threads Threads - Zugriff auf Ressourcen ohne(Lock, Synchronized)

zac12

Mitglied
Guten Abend Zusammen,
Ich beziehe mich auf das Beispiel von Oracle. Um einen Deadlock hier zu verhindern würde man ja am einfachsten die Klasse Friends anpassen und ein Lock setzen. Nun möchte ich jedoch die Threads in der Methode doSomething() "kontrollieren", wie könnte solch ein Design aussehen?, mir fehlt gerade etwas die Idee?

Danke für eure Ideen

Danke für euer Feedback

Java:
public class Deadlock {


   
    void Something() throws InterruptedException {
       
        final Friend alphonse = new Friend("Alphonse");
        final Friend gaston = new Friend("Gaston");
       
       
        Thread gastonThread = new Thread(new Runnable() {
            public  void run() {
                alphonse.bow(gaston);
        }, "Gaston");
        }
       
        Thread alphonseThread = new Thread(new Runnable() {
            public  void run() {
                gaston.bow(alphonse);
            }, "Alphonse");
        }
               
       
        alphonseThread.start();
        gastonThread.start();
        alphonseThread.join();
        gastonThread.join();

        }


    public static void main(String[] args) throws InterruptedException {
        Deadlock d = new Deadlock();
        d.doSomething();
    }
}

class Friend {
    private final String name;
//    private static final Object globalLock = new Object();

    public Friend(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public synchronized  void bow(Friend bower) {
        // synchronized (globalLock){
        System.out.format("%s: %s" + "  has bowed to me!%n", this.name,
                bower.getName());
        bower.bowBack(this);
         }
   

    public synchronized void bowBack(Friend bower){
        // synchronized (globalLock){
        System.out.format("%s: %s" + " has bowed back to me!%n", this.name,
                bower.getName());
         }
    }
 
Ohne einen Lock funktioniert das nicht. Allerdings ist es egal, wo und was du sperrst solange du damit den Zugriff auf deine Ressourcen unterbindest.
Du könnstes beispielsweise ein Objekt erstellen, was beide Ressource (Friends) enthält. Damit umgehst du die Situation, dass du beide Objekte einzeln sperrst und in deinen Deadlock läufst.
Nennen wir es einfach mal Friendship^^

Java:
class Friendship {
Friend a;
Friend b;
}
Der synchronized-Block sähe dann so aus.
Java:
synchronized  (friendship)
{
  alphonse.bow(gaston);
}
 
Danke für deine Antwort, ich dachte eventuell geht es irgendwie indem ich die Threads aktiviere und deaktiviere aber alle Versuche bei mir sind gescheitert. Ich denke deine Idee, ist auch sehr Schick🙂
Danke für deine Zeit!!
Gruss
 

Zurück
Oben