一、线程的中断
1、检查线程中断的函数
isInterrupted()和thread类的静态方法Thread.interrupted()
2、中断线程的函数
interrupt(),内部实现也是基于jni实现的
二、线程的休眠
1、sleep()方法
public static native void sleep(long millis) throws InterruptedException;
也是使用JNI实现的在预期的时间中断线程的执行,在这段空闲时间,线程不占用cpu任何资源,当它继续执行的cpu时钟来临时,jvm会选中它继续执行。
即,当线程的休眠时间结束了,jvm会分给他cpu时钟,线程继续执行他的指令
2、TimeUnit.SECONDS.sleep()方法,内部是对sleep()方法的包装,进行单位转换,源码
public void sleep(long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); Thread.sleep(ms, ns); } }
三、等待线程的终止
一些情况下,我们必须等待线程的终止。----使用join()方法
当一个线程对象的join()方法被调用时,调用他的这个线程将被挂起,知道这个线程对象完成他的任务。
两个线程类
package com.concurrent.threadManager; import java.util.Date; import java.util.concurrent.TimeUnit; public class DataSourcesLoader implements Runnable { @Override public void run() { System.out.println("Beginning DataSourcesLoader : " + new Date()); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("DataSourcesLoader has finished loading : " + new Date()); } }
package com.concurrent.threadManager; import java.util.Date; import java.util.concurrent.TimeUnit; public class NetworkConnectionsLoader implements Runnable { @Override public void run() { System.out .println("Beginning NetworkConnectionsLoader : " + new Date()); try { TimeUnit.SECONDS.sleep(6); } catch (InterruptedException e) { e.printStackTrace(); } System.out .println("NetworkConnectionsLoader has finished NetworkConnectionsLoader : " + new Date()); } }
测试函数public void testDataSourcesLoader() { DataSourcesLoader dataSourcesLoader = new DataSourcesLoader(); Thread thread = new Thread(dataSourcesLoader, "dataSourceThread"); NetworkConnectionsLoader networkConnectionsLoader = new NetworkConnectionsLoader(); Thread thread2 = new Thread(networkConnectionsLoader, "networkConnectionsLoader"); thread.start(); thread2.start(); try { thread.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out .println("Main : Configuration has been loaded " + new Date()); }
这样打印的结果就是Beginning DataSourcesLoader : Thu Jun 11 19:30:43 CST 2015 Beginning NetworkConnectionsLoader : Thu Jun 11 19:30:43 CST 2015 DataSourcesLoader has finished loading : Thu Jun 11 19:30:47 CST 2015 NetworkConnectionsLoader has finished NetworkConnectionsLoader : Thu Jun 11 19:30:49 CST 2015 Main : Configuration has been loaded Thu Jun 11 19:30:49 CST 2015
Main会在最后打印,因为一直要等待thread和thread2执行完成