Threads - Java

  • Thread
    • To achieve concurrency/parallelism
    • Priority of main thread is 5
  • States of Thread
    • Thread States
    • New
      • Create instance of thread class
      • Thread var = new Thread();
    • Running
      • var.start(); => run() method will be called
    • Suspended
      • Temporarily suspend the activity of a thread, Resume
    • Blocked
      • Access a resource, Used by some other process/thread, Once resource released then resume
    • Terminated
      • No resume, Halts execution
  • Commands
    • Creating Thread Using Class, Can't extend any other class
        ClassName var = new ClassName();
        public class ClassName extends Thread {
          // override
          public void run() {}
        }
      
    • Creating Thread Using Interface
        ClassName var1 = new ClassName();
        Thread var = new Thread(var1);
        public class ClassName implements Runnable {
          // redefined
          public void run() {}
        }
      
    • Static Methods
      • Thread.sleep()
      • Thread.currentThread()
      • Thread.activeCount()
      • Thread.yield()
    • Object Methods
      • var.start()
      • var.setName()
      • var.getName()
      • var.join()
    • synchronized => Synchronies the execution of threads, Used before function name
Share: