守护线程
Java中有两种线程,一种是用户线程,另一种是守护线程。
用户线程是指用户自定义创建的线程,主线程停止,用户线程不会停止。
守护线程当进程不存在或主线程停止,守护线程也会被停止
public class 守护线程 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
String name = Thread.currentThread().getName();
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("name:" + name + ">>>"+i);
}
});
t.setDaemon(true);
t.start();
System.out.println("执行完成了");
}
}
线程等待
线程等待的两种方式:sleep、wait
面试:区别
- sleep是Thread类的方法,wait是Object的方法
- sleep不会释放锁对象,wait会释放锁
- wait、notify、notifyAll方法都必须在synchronized代码块中使用,sleep可以在任意位置使用
- sleep()方法通过指定时间导致程序阻塞,当指定的时间到了会自动恢复运行状态。wait需要通过调用notify()、notifyAll方法后才能进入运行状态。
等待唤醒案例
例:模拟人进站和出站,保证进站了才可以出站,出站了才能进站
/**
* 模拟人进站和出站,保证进站了才可以出站,出站了才能进站
* @author wcong
* @version 1.0
* @date 2020-08-28 14:25
*/
public class 等待唤醒案例 {
public static void main(String[] args) {
State state = new State();
Thread t1 = new Thread(new InBus(state));
Thread t2 = new Thread(new OutBus(state));
t1.start();
t2.start();
}
static class State {
static String flag = "已出站";
}
/**
* 进站对象
*/
static class InBus implements Runnable {
private State state;
InBus(State state) {
this.state = state;
}
@Override
public void run() {
while (true){
synchronized (this.state) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ("已进站".equals(State.flag)) {
// 已进站,不可再进站,等待出站
try {
this.state.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
State.flag = "已进站";
System.out.println("已进站");
state.notifyAll();
}
}
}
}
/**
* 出站对象
*/
static class OutBus implements Runnable {
private State state;
public OutBus(State state) {
this.state = state;
}
@Override
public void run() {
while(true){
synchronized (this.state) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 已经出站了,不能再出站,等待进站
if("已出站".equals(State.flag)){
try {
this.state.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
State.flag = "已出站";
System.out.println("已出站");
state.notifyAll();
}
}
}
}
}