Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      Thread Control

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      Thread Control

      Java Thread Control

      Core Java provides complete control over multithreaded program. You can develop a multithreaded program which can be suspended, resumed, or stopped completely based on your requirements. There are various static methods which you can use on thread objects to control their behavior.

      Methods for Controlling Java Thread

      Following table lists down the methods for controlling a thread in Java:
      Sr.No.
      Method & Description
      1
      public void suspend()
      This method puts a thread in the suspended state and can be resumed using resume() method.
      2
      public void stop()
      This method stops a thread completely.
      3
      public void resume()
      This method resumes a thread, which was suspended using suspend() method.
      4
      public void wait()
      Causes the current thread to wait until another thread invokes the notify().
      5
      public void notify()
      Wakes up a single thread that is waiting on this object's monitor.
      Be aware that the latest versions of Java has deprecated the usage of suspend( ), resume( ), and stop( ) methods and so you need to use available alternatives.

      Example of Thread Control in Java

      class RunnableDemo implements Runnable {
      public Thread t;
      private String threadName;
      boolean suspended = false;
      
      RunnableDemo( String name) {
      threadName = name;
      System.out.println("Creating " + threadName );
      }
      public void run() {
      System.out.println("Running " + threadName );
      try {
      for(int i = 10; i > 0; i--) {
      System.out.println("Thread: " + threadName + ", " + i);
      // Let the thread sleep for a while.
      Thread.sleep(300);
      synchronized(this) {
      while(suspended) {
      wait();
      }
      }
      }
      } catch (InterruptedException e) {
      System.out.println("Thread " + threadName + " interrupted.");
      }
      System.out.println("Thread " + threadName + " exiting.");
      }
      
      public void start () {
      System.out.println("Starting " + threadName );
      if (t == null) {
      t = new Thread (this, threadName);
      t.start ();
      }
      }
      void suspend() {
      suspended = true;
      }
      synchronized void resume() {
      suspended = false;
      notify();
      }
      }
      
      public class TestThread {
      
      public static void main(String args[]) {
      
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
      
      try {
      Thread.sleep(1000);
      R1.suspend();
      System.out.println("Suspending First Thread");
      Thread.sleep(1000);
      R1.resume();
      System.out.println("Resuming First Thread");
      R2.suspend();
      System.out.println("Suspending thread Two");
      Thread.sleep(1000);
      R2.resume();
      System.out.println("Resuming thread Two");
      } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
      }try {
      System.out.println("Waiting for threads to finish.");
      R1.t.join();
      R2.t.join();
      } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
      }
      System.out.println("Main thread exiting.");
      }
      }
      The above program produces the following output

      Output

      Creating Thread-1
      Starting Thread-1
      Creating Thread-2
      Starting Thread-2
      Running Thread-1
      Thread: Thread-1, 10
      Running Thread-2
      Thread: Thread-2, 10
      Thread: Thread-1, 9
      Thread: Thread-2, 9
      Thread: Thread-1, 8
      Thread: Thread-2, 8
      Thread: Thread-1, 7
      Thread: Thread-2, 7
      Suspending First Thread
      Thread: Thread-2, 6
      Thread: Thread-2, 5
      Thread: Thread-2, 4
      Resuming First Thread
      Suspending thread Two
      Thread: Thread-1, 6
      Thread: Thread-1, 5
      Thread: Thread-1, 4
      Thread: Thread-1, 3
      Resuming thread Two
      Thread: Thread-2, 3
      Waiting for threads to finish.
      Thread: Thread-1, 2
      Thread: Thread-2, 2
      Thread: Thread-1, 1
      Thread: Thread-2, 1
      Thread Thread-1 exiting.
      Thread Thread-2 exiting.
      Main thread exiting.