Posts

Showing posts from May, 2022

Deadlock

  Deadlock Deadlock in Java means a thread is waiting for an object lock that is acquired by another thread, and second thread is waiting for a object lock that acquired by the first thread. For example, two boys are playing, boy 1 has a car, boy 2 has a pistol, they both want to play with each other's toys, but they don't want to put down their own toys, which creates a deadlock. CODE: package Thread ; ​ public class DeadLock {     public static void main ( String [] args ) {         play boy1 = new play ( "Mike" , 0 );         play boy2 = new play ( "James" , 1 );         boy1 . start ();         boy2 . start ();   } } ​ //1.Toy 1 class Toy1 {} //2.Toy 2 class Toy2 {} ​ //play class play extends Thread {     //simulate only one resource is available by using static     static Toy1 t1 = new Toy1 ();     static Toy2 t2 =...

Multithreading - 3 unsafe thread case & solution (synchronized)

  3 unsafe thread case & solution 1. Unsafely buy ticket package ThreeUnsafeThreadCase ; ​ public class ButTicket { ​     public static void main ( String [] args ) {         BuyTicket buyTicket = new BuyTicket ();         new Thread ( buyTicket , "A" ). start ();         new Thread ( buyTicket , "B" ). start ();         new Thread ( buyTicket , "C" ). start ();   } } class BuyTicket implements Runnable {     boolean flag = true ;     int numT = 10 ;     @Override     public void run () {         while ( flag ){             buy ();       }   }     private void buy (){         if ( numT <= 0 ){             flag = false ;             ret...