Java Topics
HubJava Collections FrameworkCollections Practice ProgramsComparable vs ComparatorGenericsIteratorArrayListLinkedListStackVectorHashMapHashtableLinkedHashMapTreeMapArrayDequeDeque Double-Ended QueuePriorityQueueHashSetLinkedHashSetTreeSetAdapter PatternBuilder PatternFactory PatternMVC PatternObserver PatternSingleton PatternDynamic ProgrammingGraphHashingHeapLinked List DSAQueue DSARecursionSearching AlgorithmsSorting AlgorithmsStack DSATime ComplexityTreesException Handling Best PracticesCustom ExceptionException Hierarchyfinally BlockException Handlingthrow aur throwstry-catchBuffered StreamsByte StreamsCharacter StreamsDeserializationFile ClassJava NIO New I/OSerializationArrays in JavaArray OperationsArray Practice ProgramsArray Interview QuestionsJagged ArrayMulti-Dimensional ArraysOne Dimensional Arraybreak aur continuedo-while Loopfor Loopif-else StatementsNested Loopsswitch-case Statementwhile LoopJava Compilation ProcessJava ki FeaturesPehla Java ProgramHistory of JavaJava EditionsJava Program StructureJDK, JRE aur JVMJava Kya Hai?Immutable StringsString Class in JavaString Interview QuestionsString MethodsString Practice ProgramsStringBufferStringBuilderComments in JavaData Types in JavaIdentifiers in JavaInput & Output in JavaJava KeywordsOperators in JavaType Casting in JavaVariables in JavaJava Coding Interview QuestionsCollections Interview QuestionsCore Java Interview QuestionsJDBC Interview QuestionsMultithreading Interview QuestionsOOPs Interview QuestionsSpring Framework Interview QuestionsJava 8 Date/Time APIDefault aur Static Methods in InterfaceFunctional InterfaceLambda ExpressionMethod ReferenceOptional ClassStream APIBatch ProcessingCallableStatementJDBC ArchitectureJDBC — Java Database ConnectivityJDBC Practice ProjectsMySQL ConnectionPreparedStatementResultSetStatement InterfaceTransaction ManagementCreating ThreadsDaemon ThreadExecutor FrameworkInter-Thread CommunicationMultithreading Practice ProgramsRunnable InterfaceSynchronizationThread ClassMultithreading IntroductionThread Life CycleThread PriorityJava Cheat SheetImportant Formulas & Key ConceptsImportant Java ProgramsJava Quick RevisionAbstract ClassAbstractionAnonymous ClassClass and ObjectConstructorEncapsulationInheritanceInner ClassInterfaceMethod OverloadingMethod OverridingObject ClassObject CloningObject-Oriented Programming OOPPolymorphismstatic Keywordsuper Keywordthis KeywordWrapper ClassesArray Practice ProgramsBasic Java Practice ProgramsCollection Practice ProgramsJDBC Practice ProgramsMultithreading Practice ProgramsOOPs Practice ProgramsPlacement Coding QuestionsString Practice ProgramsBanking SystemChat ApplicationE-Commerce Backend — Spring Boot REST APIEmployee Management SystemLibrary Management SystemSpring Boot Fullstack ProjectStudent Management SystemCookies in ServletExpression Language ELGenericServletHttpServletJavaServer Pages JSPJSP TagsMVC ArchitectureHttpServletRequest & HttpServletResponseServlet IntroductionServlet Life CycleSession TrackingDependency InjectionSpring BeansSpring CoreSpring FrameworkAPI GatewaySpring Cloud Config ServerDocker DeploymentEureka Server — Service DiscoverySpring Boot CRUD ApplicationException Handling in Spring BootJWT AuthenticationREST API in Spring BootSpring SecuritySpring BootSpring Data JPAValidation in Spring Boot
Multithreading Practice Programs
Last Updated : 26 May, 2026
title: Multithreading Programs
Multithreading26 words3 headingsExamples included
title: Multithreading Programs description: Multithreading ke practice programs
1. Odd-Even using two threads
class OddEven {
static int N = 10;
static int count = 1;
static final Object lock = new Object();
static void printOdd() {
while (count <= N) {
synchronized (lock) {
if (count % 2 != 0) {
System.out.println("Odd: " + count++);
lock.notify();
} else {
try { lock.wait(); } catch (InterruptedException e) { }
}
}
}
}
static void printEven() {
while (count <= N) {
synchronized (lock) {
if (count % 2 == 0) {
System.out.println("Even: " + count++);
lock.notify();
} else {
try { lock.wait(); } catch (InterruptedException e) { }
}
}
}
}
public static void main(String[] args) {
new Thread(OddEven::printOdd).start();
new Thread(OddEven::printEven).start();
}
}
2. Thread-safe Singleton
java exampleWoHoTech
class Singleton {
private static volatile Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}3. Parallel sum using threads
int[] arr = new int[1000];
for (int i = 0; i < arr.length; i++) arr[i] = i + 1;
AtomicLong totalSum = new AtomicLong(0);
int chunkSize = 250;
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 4; i++) {
final int start = i * chunkSize;
final int end = start + chunkSize;
Thread t = new Thread(() -> {
long sum = 0;
for (int j = start; j < end; j++) sum += arr[j];
totalSum.addAndGet(sum);
});
threads.add(t);
t.start();
}
for (Thread t : threads) t.join();
System.out.println("Total: " + totalSum.get()); // 500500
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Multithreading Practice Programs.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java topic.
Search Terms
java, java programming, core java, java master course, java notes, master, course, multithreading
Related Java Topics
Continue learning this concept
MultithreadingMultithreading Introductiontitle: Thread IntroductionMultithreadingCreating Threadstitle: Creating Threads in JavaMultithreadingDaemon Threadtitle: Daemon Thread in JavaMultithreadingExecutor Frameworktitle: Executor Framework in JavaMultithreadingInter-Thread Communicationtitle: Inter-Thread CommunicationMultithreadingRunnable Interfacetitle: Runnable Interface in Java