Thursday, 12 January 2017

Write a program to create deadlock between two threads.

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other to release a lock.

Code:
package com.javakickoff
public class MyDeadlockClass {

 String str1 = "Oracle";
 String str2 = "MySQL";
 
 Thread trd1 = new Thread("My Thread 1"){
  public void run(){
  while(true){
     synchronized(str1){
        synchronized(str2){
           System.out.println(str1 + str2);
     }
    }
   }
  }
 };
 
 Thread trd2 = new Thread("My Thread 2"){
  public void run(){
  while(true){
     synchronized(str2){
        synchronized(str1){
           System.out.println(str2 + str1);
     }
    }
   }
  }
 };
 
 public static void main(String a[]){
  MyDeadlockClass mdl = new MyDeadlockClass();
  mdl.trd1.start();
  mdl.trd2.start();
 }
}

No comments:

Post a Comment