对于终止运行中的线程,Thread类原本提供了一个人方法:stop();但方法已经被禁用。就目前而言,我们可以利用线程的休眠和中断机制,在子线程中有意地为调度线程安排中断机会。
下面例子就是利用线程的休眠和中断机制来终止线程。【StopThread】
/** * StopThread.java * 版权所有(C) 2011 cuiran2001@163.com * 创建:崔冉 2011-1-11 下午03:36:26 */ package com.cayden.thread7233; /** * @author 崔冉 * @version 1.0.0 * @desc */ public class StopThread { /** * @param args */ public static void main(String[] args) throws InterruptedException{ // TODO Auto-generated method stub MyThread thread1=new MyThread(); thread1.start(); Thread.sleep(5000); synchronized(thread1){ thread1.interrupt(); } } } class MyThread extends Thread { public void run(){ for(int i=0;i<10000;i++){ System.out.println("<"+i+">线程运行中..."); try{ Thread.sleep(1000); }catch (InterruptedException e) { System.out.println("线程被中止"); break; } } } }
但对于复杂的场景,可以根据这个模型来设计线程的终止机制。在和终止线程的方法中,join()方法来等待线程结束,join()方法并不能终止某线程。而是提供了一个阻塞当前线程,等待某线程终止的途径。对join()方法简单说明:
①voidjoin():一直阻塞当前线程,等待线程结束。在等待过程中,如果遇上中断请求,则抛出InterruptedException异常。
②voidjoin(longtimeout):在timeout指定的毫秒时间内阻塞当前线程,等待线程结束。在等待过程中,如果遇上中断请求,则抛出InterruptedException异常。
③voidjoin(longtimeout,intnanos):在timeout指定的毫秒+nanos指定的微妙时间内阻塞线程,等待线程结束。在等待过程中,如果遇上中断请求,则抛出InterruptedException异常。
代码如下:【JoinThread】
/** * JoinThread.java * 版权所有(C) 2011 cuiran2001@163.com * 创建:崔冉 2011-1-11 下午04:03:40 */ package com.cayden.thread7233; /** * @author 崔冉 * @version 1.0.0 * @desc */ public class JoinThread { /** * @param args */ public static void main(String[] args) throws InterruptedException{ // TODO Auto-generated method stub TestThread thread1=new TestThread(); thread1.start(); long beginTime=System.currentTimeMillis(); thread1.join(); long endTime=System.currentTimeMillis(); System.out.println("等待"+(endTime-beginTime)/1000+"秒后线程终止"); } } class TestThread extends Thread { public void run(){ for(int i=0;i<10;i++){ System.out.println("<"+i+">线程运行中..."); try{ Thread.sleep(1000); }catch (InterruptedException e) { e.printStackTrace(); } } } }
用Thread类的yield()方法可以使线程主动让出CPU时间片,会的就绪状态。等到JVM调度器再次选中该线程。【YieldThread】
<!--EndFragment-->/** * YieldThread.java * 版权所有(C) 2011 cuiran2001@163.com * 创建:崔冉 2011-1-12 上午09:03:25 */ package com.cayden.thread7233; /** * @author 崔冉 * @version 1.0.0 * @desc */ public class YieldThread { /** * @param args */ public static void main(String[] args) throws InterruptedException{ // TODO Auto-generated method stub SleepingThread thread1=new SleepingThread(1); SleepingThread thread2=new SleepingThread(2); thread1.start(); thread2.start(); Thread.sleep(5000); thread1.yield(); if(thread1.isAlive()){ System.out.println("线程1仍然存活"); } } } class SleepingThread extends Thread { private int no=0; public SleepingThread(int no){ this.no=no; } public void run(){ for(int i=0;i<10;i++){ System.out.println("<"+i+">"+this.no+"线程运行中..."); try{ Thread.sleep(1000); }catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } } }
<!--EndFragment-->
<!--EndFragment-->
1267

被折叠的 条评论
为什么被折叠?



