Friday, August 4, 2023

Thread class in Java - 4

 4. Creating multiple threads

class Multi implements Runnable

{

String name;

Thread t;

Multi(String s)

{

name=s;

t=new Thread(this,name);

System.out.println("new thread "+t);

t.start();

}

public void run()

{

try


{

for(int i=5;i>0;i--)

{

System.out.println(name+" : "+i);

Thread.sleep(1000);

}

}

catch(InterruptedException e)

{

System.out.println(name + "interrupted");

}

System.out.println(name + "exiting");

}

}

class T4Demo

{

public static void main(String args[])

{

new Multi("one");

new Multi("two");

new Multi("three");

try

{

//wait for the other thread

Thread.sleep(10000);

}

catch(InterruptedException e)

{

System.out.println("main thread interrupted ");

}

System.out.println("exiting main thread ");

}

}

o/p:------------------------------------------------------------------------------


class Multi implements Runnable

{

String name;

Thread t;

Multi(String s)

{

name=s;

t=new Thread(this,name);

System.out.println("new thread "+t);

t.start();


}

public void run()

{

try

{

for(int i=5;i>0;i--)

{

System.out.println(name+" : "+i);

Thread.sleep(1000);

}

}

catch(InterruptedException e)

{

System.out.println(name + "interrupted");

}

System.out.println(name + "exiting");

}

}

class T4Demo

{

public static void main(String args[])

{

new Multi("one");

new Multi("two");

new Multi("three");

try

{

//wait for the other thread

Thread.sleep(10000);

}

catch(InterruptedException e)

{

System.out.println("main thread interrupted ");

}

System.out.println("exiting main thread ");

}

}

o/p: ---------------- -----------------------------------

ddmc@ddmc-desktop:~$ java T4Demo

new thread Thread[one,5,main]

new thread Thread[two,5,main]

new thread Thread[three,5,main]

one : 5

two : 5

three : 5

one : 4


three : 4

two : 4

one : 3

three : 3

two : 3

one : 2

three : 2

two : 2

one : 1

three : 1

two : 1

threeexiting

twoexiting

oneexiting

exiting main thread

No comments:

Post a Comment

Complete Works of Swami Vivekananda [Volume 8,Page - 2069]

  Complete Works of Swami Vivekananda [ Volume 8, Page - 2069] Jesus Christ was God — the Personal God become man. He has manifested Himsel...