Home > Software design >  setPriority() method and interrupt() method is not executing
setPriority() method and interrupt() method is not executing

Time:05-31

In the code below I am trying to implement synchronization. The code works perfectly fine. But when I try to use the setPriority() method or interrupt() method it does not give me the desired output. Can anyone let me know what is going wrong here?

Code:

class Show{
    
    public synchronized void assignjob(String jobname) {
        for(int i=0; i<5;i  ) {
            
            System.out.println("Your new job role is:" jobname);
            
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Thread Interrupted");
            }
        }
        
    }
}

class MyThread extends Thread{
    
    Show s;
    String jobname;
    
    MyThread(Show s, String jobname)
    {
        this.s=s;
        this.jobname=jobname;
    }
    
    public void run() {
        s.assignjob(jobname);
    }
}

public class SynchronizationExamples {

    public static void main(String[] args) {
    
        Show s=new Show();
        MyThread t1= new MyThread(s,"junior developer");
        MyThread t2=new MyThread(s,"Manager");
        MyThread t3= new MyThread(s,"Logistic Officer");
        
        t1.setPriority(4);
        t1.start();
        t3.setPriority(7);
        t3.start();
        t2.interrupt();
        t2.setPriority(6);
        t2.start();

    }

}

Output:

The output here is not according to the priority set in the code snippet above and neither is the interrupt call handled.

Your new job role is:junior developer
Your new job role is:junior developer
Your new job role is:junior developer
Your new job role is:junior developer
Your new job role is:junior developer
Your new job role is:Logistic Officer
Your new job role is:Logistic Officer
Your new job role is:Logistic Officer
Your new job role is:Logistic Officer
Your new job role is:Logistic Officer
Your new job role is:Manager
Your new job role is:Manager
Your new job role is:Manager
Your new job role is:Manager
Your new job role is:Manager

CodePudding user response:

I think you need to understand the meaning of setPriority. Thread.setPriority does not set the execution order of threads but helps the thread scheduler to decide which thread should be given priority when allocating the CPU.

This answer can give you more details.

And regarding the interrupt method, you have it in the wrong place.

CodePudding user response:

You are interrupting Thread 2 even before it has started , so It's not going to throw that exception that you are hoping it should .

put that interrupt statement after T2.start()

  • Related