守护线程与非守护线程:
java中有两条线程:1.守护线程,2.非守护线程(用户线程)
守护线程与main主线程同时销毁,而用户线程与主线程无关
用户线程 可使用setDaemon(true)方法设置为守护线程
多线程运行状态:
- 新建
- 准备(就绪)
- 运行
- 休眠(阻塞)
-
停止
线程运行状态
线程运行状态
join方法:
join作用:让其他线程变为等待,比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
class JoinThread implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "---i:" + i);
}
}
}
public class JoinThreadDemo {
public static void main(String[] args) {
JoinThread joinThread = new JoinThread();
Thread t1 = new Thread(joinThread);
Thread t2 = new Thread(joinThread);
t1.start();
t2.start();
try {
//其他线程变为等待状态,等t1线程执行完成之后才能执行join方法。
t1.join();
} catch (Exception e) {
}
for (int i = 0; i < 100; i++) {
System.out.println("main ---i:" + i);
}
}
}
应用: t1,t2,t3 三个线程如何按顺序执行?(利用join方法)
public class SyncDemo{
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "运行" + "---" + i);
}
});
Thread t2 = new Thread(() -> {
try {
t1.join();//与t1有关,会使编译器放弃重排序
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "运行" + "---" + i);
}
});
Thread t3 = new Thread(() -> {
try {
t2.join();//与t2有关,会使编译器放弃重排序
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "运行" + "---" + i);
}
});
t1.start();
t2.start();
t3.start();
}
}
网友评论