Click here to Skip to main content
15,844,754 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I developing a program which determine the long lasting thread. There are 5 threads with different priorities and two threads of highest priorities are kept to sleep.Also isAlive() method is used to check whether the thread is alive or not and based on that the long lasting thread is determined,but it runs in infinite loop instead of giving long lasting thread...! below is the code
------------------------------------------------------------------
Java
import java.util.*;
class ThreadDemo extends Thread
{
    Thread t;
    String name;
    int priority;

    ThreadDemo(int priority,String name)
    {
        this.name=name;
        this.priority=priority;
        t=new Thread(this,name);
        System.out.println("New Thread "+t);
        t.start();
    }
    public void run()
    {
            int p=t.getPriority();
            try
            {
                if(p==9 || p==8)
                {
                    t.sleep(2000);
                }
                else
                {
                    System.out.println(t.currentThread()+"is alive?"+t.isAlive());
                }
                while(t.isAlive())
                {
                    System.out.println("Long lasting thread:"+t.getName());
                }

            }
            catch(InterruptedException ie)
            {
                System.out.println("Thread Interrupted...!");
            }

    }
}
class MainThread
{
    public static void main(String args[])
    {
        //ThreadDemo a,b,c,d,e;
        new ThreadDemo(5,"One");
        new ThreadDemo(6,"Two");
        new ThreadDemo(7,"Three");
        new ThreadDemo(8,"Four");
        new ThreadDemo(9,"Five");

    }
}
Posted
Updated 25-Oct-22 20:38pm

1 solution

There is nothing strange in the observed beaviour: you explicitely put threads with priorities different from 8 and 9 in a infinite pauseless loop.
 
Share this answer
 
Comments
A94 24-Aug-15 9:10am    
Then how to compare the priorities of the threads and put the thread to sleep which has higher priority and determine if it alive or not

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900