java code for deadlock situation? -


here code

public class testdeadlockexample1 {      public static void main(string[] args) {               final string resource1 = "xyz";               final string resource2 = "pqr";               // t1 tries lock resource1 resource2               thread t1 = new thread() {                 public void run() {                     synchronized (resource1) {                      system.out.println("thread 1: locked resource 1");                       try { thread.sleep(10000);} catch (exception e) {}                       synchronized (resource2) {                       system.out.println("thread 1: locked resource 2");                      }                    }                 }               };                // t2 tries lock resource2 resource1               thread t2 = new thread() {                 public void run() {                   synchronized (resource2) {                     system.out.println("thread 2: locked resource 2");                      try { thread.sleep(10000);} catch (exception e) {}                      synchronized (resource1) {                       system.out.println("thread 2: locked resource 1");                     }                   }                 }               };                 t1.start();               t2.start();               system.out.println("completed");           }   }   here    t1.start();    t2.start();    system.out.println("completed"); 

here

in t1.start() , t2.start() written in sequential order, doubt both thread starts @ same or not or t1 starts, executes comes t2 , executes, if correct, how becomes deadlock situation..i want know execution of these threads

i have learned prevent deadlocks, need make synchronized block consistently same.

          public void run() {                 synchronized (resource1) {                 synchronized (resource2) {                  system.out.println("thread 1: locked resource 1");                  system.out.println("thread 1: locked resource 2");                  try { thread.sleep(10000);} catch (exception e) {}                  }                }             }   

and

        thread t2 = new thread() {             public void run() {               synchronized (resource1) {               synchronized (resource2) {                 system.out.println("thread 2: locked resource 2");                 system.out.println("thread 2: locked resource 1");                 try { thread.sleep(10000);} catch (exception e) {}                 }               }             }           };   

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

Augmenting Latin Hypercube Points in MATLAB -