Visualizzazione dei risultati da 1 a 3 su 3

Discussione: Blocco di thread

  1. #1
    Utente bannato
    Registrato dal
    Sep 2012
    Messaggi
    465

    Blocco di thread

    codice:
    // An example of deadlock.
    class A {
      synchronized void foo(B b) {
        String name = Thread.currentThread().getName();
    
        System.out.println(name + " entered A.foo");
    
        try {
          Thread.sleep(1000);
        } catch(Exception e) {
          System.out.println("A Interrupted");
        }
    
        System.out.println(name + " trying to call B.last()");
        b.last();
      }
    
      synchronized void last() {
        System.out.println("Inside A.last");
      }
    }
    
    class B {
      synchronized void bar(A a) {
        String name = Thread.currentThread().getName();
        System.out.println(name + " entered B.bar");
    
        try {
          Thread.sleep(1000);
        } catch(Exception e) {
          System.out.println("B Interrupted");
        }
    
        System.out.println(name + " trying to call A.last()");
        a.last();
      }
    
      synchronized void last() {
        System.out.println("Inside A.last");
      }
    }
    
    class Deadlock implements Runnable {
      A a = new A();
      B b = new B();
    
      Deadlock() {
        Thread.currentThread().setName("MainThread");
        Thread t = new Thread(this, "RacingThread");
        t.start();
    
        a.foo(b); // get lock on a in this thread.
        System.out.println("Back in main thread");
      }
    
      public void run() {
        b.bar(a); // get lock on b in other thread.
        System.out.println("Back in other thread");
      }
    
      public static void main(String args[]) {
        new Deadlock();
      }
    }
    Perché se correggo il codice in questo modo:

    codice:
    Deadlock() {
        Thread.currentThread().setName("MainThread");
        Thread m = new Thread(this, "prova");
        m.start();
        Thread t = new Thread(this, "RacingThread");
        t.start();
        a.foo(b); // get lock on a in this thread.
        System.out.println("Back in main thread");
      }
    non ottengo 3 thread?

  2. #2
    Dovresti avere con quella modifica due thread che entrano in visita partendo da B ed uno che entra da A fino a B

    Invece che output ti dà?

  3. #3
    Utente bannato
    Registrato dal
    Sep 2012
    Messaggi
    465
    codice:
    MainThread entered A.foo
    prova entered B.bar
    MainThread trying to call B.last()
    prova trying to call A.last()

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.