Thread的基础用法
属性
ID
名称
状态
• NEW:安排了⼯作,还未开始⾏动
• RUNNABLE:可⼯作的.⼜可以分成正在⼯作中和即将开始⼯作.
• BLOCKED:这⼏个都表⽰排队等着其他事情(锁竞争引起)
• WAITING:这⼏个都表⽰排队等着其他事情(”死等“,以及wait引起)
• TIMED_WAITING:这⼏个都表⽰排队等着其他事情(sleep,超时join引起)
• TERMINATED:⼯作完成了.
优先级
是否是后台进程
后台进程
前台进程
需要在调用start方法前调用setDaemon()方法设置是否为后台进程,
手动创建的线程都是前台进程
是否存活
下面我们用一个代码演示一下
public class ThreadText3 {
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
System.out.println("这个线程正在运行");
});
System.out.println(thread.isAlive());
thread.start();
System.out.println(thread.isAlive());
thread.join();
System.out.println(thread.isAlive());
}
}
是否被中断
方法一:利用一个boolean类型变量
public class ThreadText3 {
static boolean flag=false;
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
while (!flag){
System.out.println("线程正在运行");
try {
sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
sleep(10000);
flag=true;
System.out.println("线程结束");
}
}
方法二:利用Thread自带的api来操作
import static java.lang.Thread.sleep;
public class ThreadText4 {
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
while (!Thread.currentThread().isInterrupted()){
System.out.println("线程正在运行");
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
Thread.sleep(1000);
//停止线程
thread.interrupt();
System.out.println("线程结束");
}
}
上述代码执行完毕,发现不能停止线程,这是为什么呢?
sleep为什么要清除标志位呢?
等待线程
sleep
import static java.lang.Thread.sleep;
public class ThreadText4 {
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
while (!Thread.currentThread().isInterrupted()){
System.out.println("线程正在运行");
try {
sleep(100);
} catch (InterruptedException e) {
break;
}
}
});
thread.start();
Thread.sleep(1000);
//停止线程
thread.interrupt();
System.out.println("线程结束");
}
}
join
public class ThreadText4 {
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
System.out.println("线程正在运行");
}
);
thread.start();
thread.join();
System.out.println("线程结束");
}
}