package thread.learn.threadbasic;
import java.sql.Time;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* 介绍线程的常用方法
* 停止,睡眠, 礼让,守护,命名,优先级,join().
*/
public class ThreadMethod {
public static void main(String[] args) {
/* 守护线程 会随着主线程结束而结束*/
Thread deamon = new Thread(new Runnable() {
public void run() {
while (true) {
}
}
});
deamon.setName("deamon");
deamon.setDaemon(true);
deamon.start();
/* 工作线程*/
Thread work = new Thread(new Runnable() {
public void run() {
//睡眠 默认毫秒 可以指定 单位.
System.out.println("start work");
try {
System.out.println(Thread.currentThread().
getName() + "I AM SLEEPING");
Thread.sleep(5000);
} catch (InterruptedException e) {
// 这里为何要 catch异常 InterruptedException?
// 因为 如果线程在休眠过程中 被调用 interrupt() 方法
// 这里将会 无法打上 isInterrupted 标记, isInterrupted 为false,
// 说明 调用的 interrupt();无效,若需要起作用,
// 这里需要再次调用interrupt()
System.out.println(Thread.currentThread().
getName() + "catch InterruptedException");
System.out.println(Thread.currentThread().
getName() + ":isInterrupted?==" + Thread.
currentThread().isInterrupted());
}
System.out.println("finish work");
}
});
//命名 非常重要, 日志分析线程问题的时候 良
// 好的线程名可以迅速定位问题.
work.setName("work_thread");
//优先级 ,高的 获取CPU 几率大.
work.setPriority(Thread.MAX_PRIORITY);
// 启动
work.start();
/* 线程停止的方法,当线程调用该方法,
线程会先被打上标记 需要停止,再停止 */
try {
Thread.sleep(1000);
// 这里等待一秒确保 work线程进入休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
work.interrupt();
//线程是否是打上了需要停止的标记
System.out.println(work.getName() +
":isInterrupted?==" + work.isInterrupted());
//是否还存活'
System.out.println(work.getName() +
":isAlive?==" + work.isAlive());
try {
// work线程执行完成后,这句代码所在的
// 线程(这里是mian线程)才执行下一句.
work.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(work.getName()
+ "isAlive?==" + work.isAlive());
}
}
* 执行结果
start work
work_threadI AM SLEEPING
work_threadcatch InterruptedException
work_thread:isInterrupted?==false
finish work
work_thread:isInterrupted?==false
work_thread:isAlive?==false
work_threadisAlive?==false
如果去掉
try {
Thread.sleep(1000);
// 这里等待一秒确保 work线程进入休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
那么运行结果为:
work_thread:isInterrupted?==true
start work
work_threadI AM SLEEPING
work_threadcatch InterruptedException
work_thread:isInterrupted?==false
finish work
work_thread:isAlive?==true
work_threadisAlive?==false
这里isInterrupted结果为true, 然后进入work线程的异常块中的时候
isInterrupted 结果为false; 分析是线程调用interrupte()方法后,会把标记打成true此时isInterrupted 为true,标识这个线程将要停止,如果这时候线程进入睡眠,那么isInterrupted 将被转为false;