Java线程编程中isAlive()和join()的使用详解
程序员文章站
2024-03-31 19:16:28
一个线程如何知道另一线程已经结束?thread类提供了回答此问题的方法。
有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isalive()。这种方法由thre...
一个线程如何知道另一线程已经结束?thread类提供了回答此问题的方法。
有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isalive()。这种方法由thread定义,它的通常形式如下:
final boolean isalive( )
如果所调用线程仍在运行,isalive()方法返回true,如果不是则返回false。但isalive()很少用到,等待线程结束的更常用的方法是调用join(),描述如下:
final void join( ) throws interruptedexception
该方法等待所调用线程结束。该名字来自于要求线程等待直到指定线程参与的概念。join()的附加形式允许给等待指定线程结束定义一个最大时间。下面是前面例子的改进版本。运用join()以确保主线程最后结束。同样,它也演示了isalive()方法。
// using join() to wait for threads to finish. class newthread implements runnable { string name; // name of thread thread t; newthread(string threadname) { name = threadname; t = new thread(this, name); system.out.println("new thread: " + t); t.start(); // start the thread } // this is the entry point for thread. 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 demojoin { public static void main(string args[]) { newthread ob1 = new newthread("one"); newthread ob2 = new newthread("two"); newthread ob3 = new newthread("three"); system.out.println("thread one is alive: "+ ob1.t.isalive()); system.out.println("thread two is alive: "+ ob2.t.isalive()); system.out.println("thread three is alive: "+ ob3.t.isalive()); // wait for threads to finish try { system.out.println("waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch (interruptedexception e) { system.out.println("main thread interrupted"); } system.out.println("thread one is alive: "+ ob1.t.isalive()); system.out.println("thread two is alive: "+ ob2.t.isalive()); system.out.println("thread three is alive: "+ ob3.t.isalive()); system.out.println("main thread exiting."); } }
程序输出如下所示:
new thread: thread[one,5,main] new thread: thread[two,5,main] new thread: thread[three,5,main] thread one is alive: true thread two is alive: true thread three is alive: true waiting for threads to finish. one: 5 two: 5 three: 5 one: 4 two: 4 three: 4 one: 3 two: 3 three: 3 one: 2 two: 2 three: 2 one: 1 two: 1 three: 1 two exiting. three exiting. one exiting. thread one is alive: false thread two is alive: false thread three is alive: false main thread exiting.
如你所见,调用join()后返回,线程终止执行。
推荐阅读
-
Java线程编程中isAlive()和join()的使用详解
-
多线程编程中条件变量和虚假唤醒(spurious wakeup)的讨论 博客分类: JAVA技术 多线程 同步 互斥 条件等待 信号量
-
多线程编程中条件变量和虚假唤醒(spurious wakeup)的讨论 博客分类: JAVA技术 多线程 同步 互斥 条件等待 信号量
-
详解Java多线程编程中CountDownLatch阻塞线程的方法
-
详解Java多线程编程中LockSupport类的线程阻塞用法
-
Java多线程编程中使用Condition类操作锁的方法详解
-
详解Java多线程编程中互斥锁ReentrantLock类的用法
-
详解Java多线程编程中LockSupport类的线程阻塞用法
-
详解Java多线程编程中CountDownLatch阻塞线程的方法
-
Java多线程编程中使用Condition类操作锁的方法详解