Friday, August 4, 2023

Thread class in Java - 5

 5. isAlive() and join()

class CreateOne implements Runnable

{

String name;

Thread t;

CreateOne(String s)

{

name=s;

t=new Thread(this,name);

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

t.start();

}

public void run()

{

try

{

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

{

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

Thread.sleep(1000);

}

}

catch(InterruptedException e)

{

System.out.println("caught");

}

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

}

}

class CreateTwo implements Runnable

{

String name;


Thread t;

CreateTwo(String s)

{

name=s;

t=new Thread(this,name);

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

t.start();

}

public void run()

{

try

{

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

{

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

Thread.sleep(500);

}

}

catch(InterruptedException e)

{

System.out.println("caught");

}

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

}

}

class T5Demo

{

public static void main(String args[])

{

CreateOne ob1=new CreateOne("One");

CreateTwo ob2=new CreateTwo("Two");

System.out.println("First thread is alive or not ---"+ob1.t.isAlive());

System.out.println("Second thread is alive or not ---"+ob2.t.isAlive());

//wait for the threads to finish

try

{

ob1.t.join();

ob2.t.join();

}

catch(InterruptedException e)

{

}

System.out.println("First thread is alive or not ---"+ob1.t.isAlive());

System.out.println("Second thread is alive or not ---"+ob2.t.isAlive());

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

}

}


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

ddmc@ddmc-desktop:~$ java T5Demo

First thread Thread[One,5,main]

First thread Thread[Two,5,main]

First thread is alive or not ---true

Second thread is alive or not ---true

One : 0

Two : 0

Two : 1

One : 1

Two : 2

Two : 3

One : 2

Two : 4

Twoexiting

One : 3

One : 4

Oneexiting

First thread is alive or not ---false

Second thread is alive or not ---false

exiting main

No comments:

Post a Comment

A physicist confesses that the electron is round and that Jesus rose from the dead. (Bengali)

একজন পদার্থবিজ্ঞানী স্বীকার করেন যে ইলেকট্রন গোলাকার এবং যিশু মৃতদের মধ্য থেকে পুনরুত্থিত হয়েছিলেন। আমার নিজের বিশ্বাস প্রমাণ দ্বারা প্রভাব...