RKTechGame | Thread Priorities & Synchronization in Java

Thread Priorities kya hoti hain?

Java threads ko priority di ja sakti hai, jo thread scheduler ko batati hai ki kaunse thread ko pehle CPU time milna chahiye. Priority number 1 se lekar 10 tak hota hai, jisme 1 sabse lowest aur 10 sabse highest priority hoti hai.

Thread Priority Example

class PriorityDemo extends Thread {
  public PriorityDemo(String name) {
    super(name);
  }
  public void run() {
    System.out.println(getName() + " running with priority " + getPriority());
  }
}
public class ThreadPriorityExample {
  public static void main(String[] args) {
    PriorityDemo t1 = new PriorityDemo("Low Priority Thread");
    PriorityDemo t2 = new PriorityDemo("Max Priority Thread");
    PriorityDemo t3 = new PriorityDemo("Normal Priority Thread");

    t1.setPriority(Thread.MIN_PRIORITY);
    t2.setPriority(Thread.MAX_PRIORITY);
    t3.setPriority(Thread.NORM_PRIORITY);

    t1.start();
    t2.start();
    t3.start();
  }
}

Output me threads ke naam ke saath unki priority bhi dikhegi.

Thread Synchronization kya hai?

Synchronization ka matlab hai ki jab multiple threads ek shared resource ya critical section ko access karte hain, toh code ko is tarah se likhna jisse data corruption ya inconsistency na ho.

Synchronization Example (Method level)

class Counter {
  private int count = 0;
  public synchronized void increment() {
    count++;
    System.out.println(Thread.currentThread().getName() + " count: " + count);
  }
  public int getCount() {
    return count;
  }
}
public class SyncExample {
  public static void main(String[] args) {
    Counter counter = new Counter();

    Runnable task = () -> {
      for (int i = 0; i < 5; i++) {
        counter.increment();
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    };

    Thread t1 = new Thread(task, "Thread-1");
    Thread t2 = new Thread(task, "Thread-2");

    t1.start();
    t2.start();
  }
}

Count incrementation sequence properly synchronized hoti hai, race condition nahi hoti.

Synchronization Block Example

class SyncBlockExample {
  private int count = 0;
  public void increment() {
    synchronized(this) {
      count++;
      System.out.println(Thread.currentThread().getName() + " synchronized count: " + count);
    }
  }
}
public class SyncBlockDemo {
  public static void main(String[] args) {
    SyncBlockExample example = new SyncBlockExample();

    Runnable task = () -> {
      for (int i = 0; i < 5; i++) {
        example.increment();
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    };

    Thread t1 = new Thread(task, "Thread-A");
    Thread t2 = new Thread(task, "Thread-B");

    t1.start();
    t2.start();
  }
}

Synchronized block ke andar ka code ek waqt mein sirf ek thread chala sakta hai.