Posts

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...

Lambda expression

  Lambda expression Why lambda? Avoid defining too many anonymous inner class Simplify the code, keep the core part of code Premise of lambda Requires a functional interface //if you want to use lambda like this way, only one line code is acceptable like = () -> System . out . println ( "I like lambda expression - lambda expression2" ); The following code illustrates the simplified process from outer class to lambda package com . lilrich . lambda ; ​ import java . sql . SQLOutput ; ​ public class TestLambda {     //2. static inner class     static class Like2 implements ILike {         @Override         public void lambda () {             System . out . println ( "I like lambda expression - static inner class" );       }   }     public static void main ( String [] args ) {         ILike like = new Like1 (); ...