commit 6428f54e148dd7423d61902ac44af46ba673e314 Author: hitanshu310 Date: Wed Dec 31 19:13:50 2025 +0530 Initial commit diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..27debe5 --- /dev/null +++ b/build.gradle @@ -0,0 +1,21 @@ +plugins { + id 'java' +} + +group = 'com.hithomelabs.dsa' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation platform('org.junit:junit-bom:5.10.0') + compileOnly 'org.projectlombok:lombok:1.18.34' + annotationProcessor 'org.projectlombok:lombok:1.18.34' + testImplementation 'org.junit.jupiter:junit-jupiter' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b6066c2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Aug 03 17:08:53 IST 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..593d6b6 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'corejava' + diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/DeadLock.java b/src/main/java/com/hithomelabs/dsa/concurrency/DeadLock.java new file mode 100644 index 0000000..eca90a1 --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/DeadLock.java @@ -0,0 +1,106 @@ +package com.hithomelabs.dsa.concurrency; +/* + * * Example of deadlock + */ + +import lombok.AllArgsConstructor; + +class Aloo{ + + public void alooSong(){ + System.out.println("Aloo ... le lo"); + } + +} + +class Kanda{ + + public void kandaSong(){ + System.out.println("kandaa ... le looo"); + } +} + +@AllArgsConstructor +class Vendor1 implements Runnable { + + Aloo aloo; + Kanda kanda; + + @Override + public void run() { + System.out.println("Vendor1 singing"); + synchronized (aloo) { + aloo.alooSong(); + + // * * sleep + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + synchronized (kanda) { + kanda.kandaSong(); + } + } + } +} + +@AllArgsConstructor +class Vendor2 implements Runnable{ + + Aloo aloo; + Kanda kanda; + + @Override + public void run() { + System.out.println("Vendor2 singing"); + synchronized (kanda){ + kanda.kandaSong(); + + // * * sleep + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + synchronized (aloo){ + aloo.alooSong(); + } + + } + } +} + +public class DeadLock { + public static void main(String[] args) throws InterruptedException { + + // * * Shared resources + Aloo aaloo = new Aloo(); + Kanda kanda = new Kanda(); + + // * * Declaring the two threads, with 2 vendors + Thread t1 = new Thread(new Vendor1(aaloo, kanda)); + Thread t2 = new Thread(new Vendor2(aaloo, kanda)); + + t1.start(); + t2.start(); + + // * * Looking at the state the threads are in + Thread.sleep(500); + System.out.println(t1 + ":" + t1.getState()); + System.out.println(t2 + ":" + t2.getState()); + System.out.println("Main thread state :" + Thread.currentThread().getState()); + + // * * Looking at the state the threads are in + Thread.sleep(1000); + System.out.println(t1 + ":" + t1.getState()); + System.out.println(t2 + ":" + t2.getState()); + System.out.println("Main thread state :" + Thread.currentThread().getState()); + + t1.join(); + t2.join(); + + } +} diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/DeadLockExampleWithLock.java b/src/main/java/com/hithomelabs/dsa/concurrency/DeadLockExampleWithLock.java new file mode 100644 index 0000000..44e8d27 --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/DeadLockExampleWithLock.java @@ -0,0 +1,112 @@ +package com.hithomelabs.dsa.concurrency; + +/* + * * An example where one vendor gets the lock but deadlock is avoided + */ + +import lombok.AllArgsConstructor; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +class Paper{ + + private static Lock lock = new ReentrantLock(); + private String message; + + public String procurePaper() { + boolean hasLock = false; + try{ + if(lock.tryLock(500, TimeUnit.MILLISECONDS)){ + hasLock = true; + return "writing on paper ..."; + } + else{ + return "Could not get lock"; + } + }catch (Exception e){ + System.out.println(e.getMessage()); + } + finally { + if (hasLock) + lock.unlock(); + } + return ""; + } + +} + +class Pen{ + + private String message; + private static Lock lock = new ReentrantLock(); + + public String procurePen(){ + boolean hasLock = false; + try{ + if(lock.tryLock(500,TimeUnit.MILLISECONDS)){ + hasLock = true; + Thread.sleep(5000); + return "Writing with pen ..."; + } + else{ + return "Could not get lock"; + } + } + catch(Exception e){ + System.out.println(e.getMessage()); + } + finally { + if(hasLock) + lock.unlock(); + } + return ""; + } + +} + +@AllArgsConstructor +class VendorWithLock1 implements Runnable{ + + Pen pen; + Paper paper; + + @Override + public void run() { + System.out.println(Thread.currentThread() + paper.procurePaper()); + System.out.println(Thread.currentThread() + pen.procurePen()); + } +} + +@AllArgsConstructor +class VendorWithLock2 implements Runnable{ + + Pen pen; + Paper paper; + + @Override + public void run() { + System.out.println(Thread.currentThread() + pen.procurePen()); + System.out.println(Thread.currentThread() + paper.procurePaper()); + } +} + +public class DeadLockExampleWithLock { + + public static void main(String[] args) throws InterruptedException { + // * * Shared resources + Pen pen = new Pen(); + Paper paper = new Paper(); + + // * * Declaring the two threads, with 2 vendors + Thread t1 = new Thread(new VendorWithLock1(pen, paper)); + Thread t2 = new Thread(new VendorWithLock2(pen, paper)); + + t1.start(); + t2.start(); + + t1.join(); + t2.join(); + } +} diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/Drop.java b/src/main/java/com/hithomelabs/dsa/concurrency/Drop.java new file mode 100644 index 0000000..91e237f --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/Drop.java @@ -0,0 +1,93 @@ +package com.hithomelabs.dsa.concurrency; + +class Producer implements Runnable{ + + Drop drop; + + Producer(Drop drop){ + this.drop = drop; + } + + // This is the produce method + + @Override + public void run() { + + for (int i = 0; i < 1000; i++) { + try { + drop.setMessage("Produced"); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + } +} + + +class Consumer implements Runnable{ + + Drop drop; + + Consumer(Drop drop){ + this.drop = drop; + } + + @Override + public void run() { + for (int i = 0; i < 1000; i++) { + try { + drop.consumeMessage(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } +} + +public class Drop { + + private String message; + private boolean consumed = true; + + public synchronized void setMessage(String message) throws InterruptedException { + + // * * Before producer produces message it has to check, if flag is true + // * * If flag is true, it means, good to produce + while(!consumed){ + this.wait(); + } + System.out.println(message); + this.message = message; + // * * Notify once production is complete + consumed = false; + this.notifyAll(); + } + + public synchronized void consumeMessage() throws InterruptedException{ + + // * * Will wait to consume unless + while(consumed){ + this.wait(); + } + System.out.println("Consumed message"); + this.message = ""; + consumed = true; + this.notifyAll(); + } + + public static void main(String[] args){ + + // * * Shared object where producer drops produce and consumer consumes it + Drop drop = new Drop(); + + // * * providing the same drop object to both producer and consumer + Thread t1 = new Thread(new Producer(drop)); + Thread t2 = new Thread(new Consumer(drop)); + + t2.start(); + t1.start(); + + } + +} diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/InterruptExample.java b/src/main/java/com/hithomelabs/dsa/concurrency/InterruptExample.java new file mode 100644 index 0000000..bfc719e --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/InterruptExample.java @@ -0,0 +1,32 @@ +package com.hithomelabs.dsa.concurrency; + +public class InterruptExample { + + public static void main(String[] args) { + Thread gaanvKaWatchman = new Thread(()->{ + while(true){ + try{ + Thread.sleep(1000); + } catch (InterruptedException e) { + System.out.println("All is not well"); + System.out.println(e); + return; + } + System.out.println("Aal izz well"); + } + }); + gaanvKaWatchman.start(); + int counter = 5; + while(counter > 0){ + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + System.out.println("Looks like watchman is awake !! :: Checking in " + counter); + counter--; + } + System.out.println("Let me check ! Watchman is asleep, wake him up"); + gaanvKaWatchman.interrupt(); + } +} diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/RaceCondition.java b/src/main/java/com/hithomelabs/dsa/concurrency/RaceCondition.java new file mode 100644 index 0000000..26ed176 --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/RaceCondition.java @@ -0,0 +1,52 @@ +package com.hithomelabs.dsa.concurrency; + +/* + * * Using Threads often leads to unpredictable outputs (non-deterministic) + * * This is when two threads simultaneously execute a block of code + * * This is called a race condition and the block of code is called the critical section + */ + + +import lombok.Getter; + +public class RaceCondition { + + // * * Creating a Runnable class Counter, having a field count that is incremented by the incrementCount method + // * * The run method increments count 1000 times + + @Getter + static class Counter implements Runnable{ + + private int counter = 0; + + // * * critical section + synchronized void incrementCounter(){ + this.counter++; + } + + @Override + public void run() { + for(int i = 0; i < 1000; i++) + incrementCounter(); + } + } + + public static void main(String[] args) throws InterruptedException { + + Counter counter = new Counter(); + + Thread t1 = new Thread(counter); + Thread t2 = new Thread(counter); + + // * * both threads attempt to increments and save simultaneously + t1.start(); + t2.start(); + + t1.join(); + t2.join(); + + System.out.println(counter.getCounter()); + + } + +} diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/StaticMethods.java b/src/main/java/com/hithomelabs/dsa/concurrency/StaticMethods.java new file mode 100644 index 0000000..f552096 --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/StaticMethods.java @@ -0,0 +1,56 @@ +package com.hithomelabs.dsa.concurrency; +import java.util.Arrays; + +public class StaticMethods { + + public static void main(String[] args) throws InterruptedException { + + // * * we are going to look at important static methods of Threads + + // * * sleep - Important thread life cycle method - passes control to other threads who want to execute + System.out.println("Sleeping for 1 second"); + Thread.sleep(1000); + + // * * Group 1 - Thread detail methods + System.out.println("Details of current thread: " + Thread.currentThread()); + + // * * Creating a runnable that sleeps fpr 5 and will use it to spawn some threads + Runnable sleepFor5 = () -> { + try { + System.out.println("Spawned new thread"); + Thread.sleep(5000); + System.out.println("Slept for 5 seconds"); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }; + + // * * Spawning some new threads + new Thread(sleepFor5).start(); + new Thread(sleepFor5).start(); + new Thread(sleepFor5).start(); + + Thread[] array = new Thread[4]; + + // * * Enumerating threads + Thread.enumerate(array); + + System.out.println("Enumerating all known threads"); + Arrays.stream(array).forEach(t -> { + System.out.println(t); + System.out.println(t.getState()); + }); + + System.out.println("Thread active count: " + Thread.activeCount()); + System.out.println("Will wait for other threads to join me"); + + Arrays.stream(array).filter(thread -> !thread.equals(Thread.currentThread())).forEach(thread -> { + try { + thread.join(); // * * Not a static method but a thread life cycle method + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }); + System.out.println("All threads are finished"); + } +} diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/ThreadSample.java b/src/main/java/com/hithomelabs/dsa/concurrency/ThreadSample.java new file mode 100644 index 0000000..7cdbf86 --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/ThreadSample.java @@ -0,0 +1,38 @@ +package com.hithomelabs.dsa.concurrency; + +public class ThreadSample extends Thread { + + @Override public void run(){ + System.out.println("Hello this is called from: " + this.getClass()); + System.out.println(Thread.currentThread()); + } + + public static void main(String[] args) { + + /* + * * There are two ways to implement a thread, one is to extend the Thread class + * * Another one is to implement the Runnable Interface + */ + + ThreadSample thread = new ThreadSample(); + + // * * Thread.run() doesn't start a new thread; just calls the method + thread.run(); + + // * * Thread.start() starts a new thread + thread.start(); + + // * * Now attempting with Runnable: + new Thread(new Runnable() { + @Override + public void run() { + System.out.println("Hello this is called from: " + this.getClass()); + System.out.println(Thread.currentThread()); + } + }).start(); + + // * * Can also be done using lamda expressions + new Thread(() -> System.out.println("Running from a lamda expression")).start(); + + } +} diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/Volatile.java b/src/main/java/com/hithomelabs/dsa/concurrency/Volatile.java new file mode 100644 index 0000000..062936c --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/Volatile.java @@ -0,0 +1,52 @@ +package com.hithomelabs.dsa.concurrency; + +import lombok.AllArgsConstructor; +import lombok.Setter; + +@Setter +class Flag{ + boolean print = true; +} + +@AllArgsConstructor +class PrintLoop implements Runnable{ + + Flag flag; + + @Override + public void run() { + int counter = 0; + while(flag.print){ + System.out.println(++counter); + } + } +} + +@AllArgsConstructor +class FlagFalse implements Runnable{ + + Flag flag; + + @Override + public void run() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + flag.setPrint(false); + } +} + +public class Volatile { + + + public static void main(String[] args) { + + Flag flag = new Flag(); + + new Thread(new PrintLoop(flag)).start(); + new Thread(new FlagFalse(flag)).start(); + + } +}