Friday, May 5, 2023

Thread, Multi Thread & setting thread priority

 single thread program

class MyThread extends Thread{

    Thread t;

    public MyThread(String msg){

        t=new Thread(msg);

    }

    public void run()

    {

        

        for(int i=1;i<=5;i++){

    try{

        t.sleep(1000);

        System.out.println(t.getName()+" : "+i);    

    }

    catch(Exception e)

    {

      e.printStackTrace();  

    }

        }

    }

}


public class Main

{

public static void main(String[] args) {

    MyThread t1=new MyThread("Theread-1"); 

t1.start();

}

}

-------------------------------------------------------------

multi thread


class MyThread extends Thread{

    Thread t;

    public MyThread(String msg){

        t=new Thread(msg);

    }

    public void run()

    {

        

        for(int i=1;i<=5;i++){

    try{

        t.sleep(1000);

        System.out.println(t.getName()+" : "+i);    

    }

    catch(Exception e)

    {

      e.printStackTrace();  

    }

        }

    }

}


public class Main

{

public static void main(String[] args) {

    MyThread t1=new MyThread("Theread-1"); 

    MyThread t2=new MyThread("Theread-2"); 

    MyThread t3=new MyThread("Theread-3"); 

t1.start();

t2.start();

t3.start();

}

}

--------------------------------------------------------

thread priority


class MyThread extends Thread{

    Thread t;

    public MyThread(String msg){

        t=new Thread(msg);

    }

    public void run()

    {

        

        for(int i=1;i<=5;i++){

    try{

        t.sleep(1000);

        System.out.println(t.getName()+" : "+i);    

    }

    catch(Exception e)

    {

      e.printStackTrace();  

    }

        }

    }

}


public class Main

{

public static void main(String[] args) {

    MyThread t1=new MyThread("Theread-1"); 

    MyThread t2=new MyThread("Theread-2"); 

    MyThread t3=new MyThread("Theread-3"); 

t1.start();

t1.setPriority(Thread.MAX_PRIORITY);

t2.start();

t3.start();

}

}