Posts

Showing posts from September, 2019

Check if booleans are same

package com.demo.demo; public class EqualBooleanDemo {   public static void main(String[] args ) { Boolean b = true ; boolean b1 = true ; Boolean b2 = new Boolean( true ); System. out .println( "b==b1 : " +( b == b1 )); System. out .println( "b==b2 : " +( b == b2 )); System. out .println( "b2==b1 : " +( b2 == b1 )); } }

Program to check rotations strings

package com.demo.demo; public class CyclicStringDemo { public static void main(String[] args ) { String s = "abc" ; String s1 = "bca" ; String s2 = "cba" ; checkCyclicString( s , s1 ); checkCyclicString( s , s2 ); } private static void checkCyclicString(String s , String s1 ) { s1 = s1 + s1 ; System. out .println( "Is cyclic : " + s1 .contains( s )); } } Output:- Is cyclic : true Is cyclic : false

Program for producer consumer

package com.demo.demo; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.stream.IntStream; public class ProducerConsumerDemo { public static void main(String[] args ) { BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(2, true ); IntStream.range(0, 4).forEach( n -> { Producer producer = new Producer( blockingQueue ); producer .start(); }); Consumer consumer = new Consumer( blockingQueue ); consumer .start(); } } class Consumer extends Thread { private BlockingQueue<String> blockingQueue ; public Consumer(BlockingQueue<String> blockingQueue ) { this . blockingQueue = blockingQueue ; } @Override public void run() { while ( true ) { try { String str = blockingQueue .take(); System. out .println( "Consuming msg : " + str ); Thread.sleep(1000); ...

Write a program to create own threadpool in Java

package com.demo.demo; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.stream.IntStream; public class ThreadPoolDemo { BlockingQueue<Runnable> blockingQueue ; List<ThreadPool> list ; private boolean stopped = false ; public ThreadPoolDemo( int size ) { blockingQueue = new ArrayBlockingQueue<>( size ); list = new ArrayList<>( size ); for ( int i = 0; i < size ; i ++) { Thread t = new ThreadPool( blockingQueue ); t .start(); } } public void stop() { stopped = true ; list .stream().forEach( m -> m .stoped()); } public boolean addTask(Runnable runnable ) throws InterruptedException { if ( stopped ) { return false ; } blockingQueue .put( runnable ); return true ; } public static void main(String[] a...