Java中的Thread isAlive()方法及其示例

java中的Thread类提供了许多非常重要的方法,以便在线程阶段被触发时理解线程的工作。Java多线程提供了两种在 isAlive()和join()方法。

null

一个线程知道另一个线程何时结束。让我们通过下图来描述线程生命周期的各个阶段,这有助于我们连接点来理解这些方法的工作原理。

图片[1]-Java中的Thread isAlive()方法及其示例-yiteyi-C++库

现在让我们更深入地讨论Thread类的isAlive()方法。基本上,这种方法在内部非常紧密地与线程的生命周期阶段并行工作。它测试该线程是否处于活动状态。如果线程已启动但尚未死亡,则该线程是活动的。从线程运行到线程不运行有一个过渡期。

run()方法返回后,线程会在短时间内停止。如果我们想知道thread类的start方法是否被调用,或者线程是否被终止,我们必须使用isAlive()方法。此方法用于确定线程是否已实际启动且尚未终止。

语法:

final boolean isAlive()

返回值: 布尔值返回

注: 返回时,如果调用该函数的线程仍在运行,则该函数返回true。否则返回false。

实例

JAVA

// Java program to Illustrate isAlive() Method
// of Thread class
// Main class extending Thread class
public class oneThread extends Thread {
// Method 1
// run() method for thread
public void run()
{
// Print statement
System.out.println( "geeks " );
// Try block to check for exceptions
try {
// making thread to sleep for 300 nano-seconds
// using sleep() method
Thread.sleep( 300 );
}
// Catch block to handle InterruptedException
catch (InterruptedException ie) {
}
// Display message when exception occured
System.out.println( "forgeeks " );
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating threads using above class as
// it is extending Thread class
oneThread c1 = new oneThread();
oneThread c2 = new oneThread();
// Starting threads
c1.start();
c2.start();
// Checking whethr thread is alive or not
// Returning boolean true if alive else false
System.out.println(c1.isAlive());
System.out.println(c2.isAlive());
}
}


输出:

geeks 
true
true
geeks 
forgeeks 
forgeeks

本文由 希瓦尼·古泰尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享