Skip to content

Latest commit

 

History

History
193 lines (153 loc) · 4.82 KB

03. Thread Priorities and Synchronization.md

File metadata and controls

193 lines (153 loc) · 4.82 KB

Thread Priorities

  • Priorities allow the thread scheduler to decide when each thread should be allowed to run.
  • Theoretically, thread with higher priority should get more CPU time than lower priority threads.
  • In practise, besides its priority, allocated CPU time depends on several factors like OS implementation of multitasking.
  • final void setPriority(int level) can be used to set priority.
  • level must be in range MIN_PRIORITY and MAX_PRIORITY.
  • NORM_PRIORITY is the default priority.
  • final int getPriority() can be called to get the priority of a thread.
class CustomThread extends Thread {

    CustomThread(String name){
        super(name);
    }

    /**
     * Runs this operation.
     */
    @Override
    public void run() {
        System.out.println("thread " + this.getName() + " exiting");
    }
}

public class Main {

    public static void main(String[] args) {
        Thread t = Thread.currentThread();

        System.out.println("main thread: " + t);

        CustomThread t1 = new CustomThread("t1");
        CustomThread t2 = new CustomThread("t2");
        CustomThread t3 = new CustomThread("t3");
        CustomThread t4 = new CustomThread("t4");

        System.out.println(t4.getPriority());
        t4.setPriority(10);
        System.out.println(t4.getPriority());
        System.out.println(t2.getPriority());

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

        try {

            System.out.println("main thread: waiting for the threads to finish");
            t1.join();
            t2.join();
            t3.join();
            t4.join();

        }catch (InterruptedException ex){
            System.out.println("main thread interrupted");
        }
        System.out.println("Main thread exiting");
    }
}

Synchronization

  • Process of making sure a shared resource is accessed by only one thread at a time.
  • Monitor is an object that is used as a mutually exclusive lock. Only one thread can own a monitor at a given time.
  • when a thread acquires a lock, it is said to have entered the monitor.
  • All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.

Ways to synchronize your code

  • using synchronized method.
class Target{
    synchronized void call(String msg){
        System.out.print("[ " + msg);
        try{
            // this causes another thread to use the cpu time. but because of synchronized keyword 
            // the call method acts like a monitor
            Thread.sleep(1000); 
        }catch (InterruptedException ex){
            System.out.println("thread interrupted");
        }
        System.out.println(" ]");
    }
}

class CustomThread implements Runnable {
     Thread thread;
     Target target;
     String msg;

    CustomThread(String msg,Target target){
        this.thread = new Thread(this);
        this.msg = msg;
        this.target = target;
    }

    /**
     * Runs this operation.
     */
    @Override
    public void run() {
        this.target.call(this.msg);
    }
}

public class Main {

    public static void main(String[] args) {
        Target target = new Target();

        CustomThread t1 = new CustomThread("hello", target);
        CustomThread t2 = new CustomThread("world",target);

        t1.thread.start();
        t2.thread.start();

        try {
            t1.thread.join();
            t2.thread.join();
        }catch (InterruptedException ex){
            System.out.println("main thread interrupted");
        }
    }
}
  • using synchronized statement
    • This is useful in cases where you are calling methods from a library, which is not a thread safe method.
class Target{
    void call(String msg){
        System.out.print("[ " + msg);
        try{
            Thread.sleep(1000);
        }catch (InterruptedException ex){
            System.out.println("thread interrupted");
        }
        System.out.println(" ]");
    }
}

class CustomThread implements Runnable {
     Thread thread;
     final Target target;
     String msg;

    CustomThread(String msg,Target target){
        this.thread = new Thread(this);
        this.msg = msg;
        this.target = target;
    }

    /**
     * Runs this operation.
     */
    @Override
    public void run() {
        synchronized(this.target) {
            this.target.call(this.msg);
        }
    }
}

public class Main {

    public static void main(String[] args) {
        Target target = new Target();

        CustomThread t1 = new CustomThread("hello", target);
        CustomThread t2 = new CustomThread("world",target);

        t1.thread.start();
        t2.thread.start();

        try {
            t1.thread.join();
            t2.thread.join();
        }catch (InterruptedException ex){
            System.out.println("main thread interrupted");
        }
    }
}