Friday, August 4, 2023

Thread class in Java - 3

 3. Creating thread by extending Thread class

class MyNewThread extends Thread

{

MyNewThread()

{

//creating new thread

super("Demo thread");

System.out.println("child thread "+this);

start();

}

public void run()

{

try

{

for(int i=0;i<5;i++)

{

System.out.println("child thread "+i);

Thread.sleep(500);

}

}

catch(InterruptedException e)

{

System.out.println("child interrupted ");

}

System.out.println("exiting child thread----");

}

}

class T3Demo

{

public static void main(String args[])

{


new MyNewThread();

try

{

for(int i=90;i<95;i++)

{

System.out.println("main thread "+i);

Thread.sleep(1000);

}

}

catch(InterruptedException e)

{

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

}

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

}

}

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

ddmc@ddmc-desktop:~$ java T3Demo

child thread Thread[Demo thread,5,main]

child thread 0

main thread 90

child thread 1

child thread 2

main thread 91

child thread 3

child thread 4

main thread 92

exiting child thread----

main thread 93

main thread 94

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...