concurrency - How to prevent this simple deadlock in java? -


this question has answer here:

i have simple example illustrates how cause deadlock:

class player {     private string name;      public player(string name) {         super();         this.name = name;     }      public synchronized void passto(player p) {         system.out.println(this.name + " passes " + p.name);         // imitate long task         (int = 0; < 1000000000; i++)             ;         p.passback(this);     }      private synchronized void passback(player p) {         system.out.println(this.name + " passes " + p.name);     } }  public class deadlock {      public static void main(string[] args) {         final player ivan = new player("ivan");         final player petro = new player("petro");          new thread(new runnable() {             public void run() {                 ivan.passto(petro);             }         }).start();         new thread(new runnable() {             public void run() {                 petro.passto(ivan);             }         }).start();     } } 

when run program causes deadlock.

what possible solutions prevent simple deadlock?

thank you!

you make public synchronized void passto(player p) method static. @ time 1 player can call passto() method , there no deadlock i.e remove cyclic dependency. change to

public static synchronized void passto(player p)


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -