Java threading

Created By: chatGPT

In Java, multithreading is a powerful feature that allows concurrent execution of two or more threads. Threads can be thought of as lightweight processes, sharing the same memory space but executing independently. To create a thread in Java, you can either extend the Thread class or implement the Runnable interface. Using the Runnable interface is generally preferred as it allows you to extend another class if needed.
class MyThread extends Thread { 
    public void run() { 
        System.out.println("Thread is running."); 
    } 
}

class MyRunnable implements Runnable { 
    public void run() { 
        System.out.println("Runnable is running."); 
    } 
}
After defining a thread or a runnable, you can start the execution using start() method for a thread and Thread class's start() method is used to begin the execution of the thread. For the runnable, you need to pass it to a Thread object and then call start() on that Thread object.
MyThread myThread = new MyThread(); 
myThread.start(); 

MyRunnable myRunnable = new MyRunnable(); 
Thread thread = new Thread(myRunnable); 
thread.start();
You can also control the thread's execution by using methods like sleep(), join(), and wait(). The sleep() method pauses the current thread for a specified amount of time. The join() method allows one thread to wait for another to finish executing. The wait() and notify() methods are used for inter-thread communication.
try { 
    Thread.sleep(1000); // sleep for 1 second 
} catch (InterruptedException e) { 
    e.printStackTrace(); 
}

myThread.join(); // wait for myThread to finish
Synchronizing threads is crucial to prevent race conditions when multiple threads access shared resources. You can achieve synchronization by using the synchronized keyword. This can be applied to methods or blocks of code to ensure that only one thread executes the critical section at a time.
public synchronized void synchronizedMethod() { 
    // critical section code 
}

public void synchronizedBlock() { 
    synchronized(this) {  
        // critical section code 
    } 
}
Java also provides the Executor Framework, which simplifies thread management. Using Executors, you can manage a pool of threads, making it easier to handle tasks and improving resource utilization. The ExecutorService interface allows you to submit tasks for execution without manually creating and managing threads.
ExecutorService executorService = Executors.newFixedThreadPool(2); 
executorService.submit(() -> { 
    System.out.println("Task executed."); 
}); 

executorService.shutdown();
Introduction And SetupVariablesData TypesIntFloatDoubleCharBooleanStringByteShortLongArrayListMethodVoidReturnParametersArgumentsControl FlowIf StatementElse StatementElse If StatementSwitch StatementCaseBreakContinueFor LoopWhile LoopDo While LoopEnhanced For LoopFunctionsStatic MethodInstance MethodConstructorOverloadingOverridingAccess ModifiersPrivateProtectedPackage PrivateOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsTernary OperatorInstanceof OperatorArrayListSetMapHashmapHashtableQueStackCommentsSingle Line CommentMulti Line CommentSyntaxSemicolonsCurly BracesParenthesesData EncapsulationInheritancePolymorphismAbstract ClassInterfaceException HandlingTry BlockCatch BlockFinally BlockThrowThrowsChecked ExceptionUnchecked ExceptionSyntax ErrorsRuntime ErrorsLogic ErrorsEvent HandlingListenersAction EventsMouse EventsKeyboard EventsWindow EventsFocus EventsKey ListenerMouse ListenerAction ListenerThreadingSynchronizationVolatile KeywordConcurrencyJava Memory Model