线程的控制
1. join线程
让一个线程等待另一个线程完成的方法:例如,main线程中调用a线程的join方法后,那么在a线程结束后,main才会继续运行(如果还有其他线程,其他线程与她两无关)。
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
});
thread.start();
thread.join();//如果不加这一句,就是交叉执行
System.out.println("子线程完了");
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
执行结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zvhLFKGW-1575043286885)(https://note.youdao.com/yws/api/personal/file/98829D7049444FADA4C31323C96D944F?method=download&shareKey=daf93550951ca2ac7beb5a038c31ee4e)]
2.守护线程:java中有两种线程
- 守护线程:deamon线程、后台线程、精灵线程。当进程不存在的时候,或者主线程停止,守护线程停止
- 用户线程:前台线程。用户自定义的线程,主线程停止,用户线程不会停止
public static void main(String[] args) {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
while (true){
System.out.println("子线程正在运行");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
//thread.setDaemon(true);//可以设置为后台线程
System.out.println("主线程停止了");
}
运行结果
3.线程睡眠:sleep##
线程睡眠使当前线程进入阻塞,放弃cpu资源。具体使用见上面代码。
4. 线程让步:yield(不常用该方式来控制并发)##
和sleep类似,但又有区别。都可以暂停线程,但是yield,强制线程进入就绪状态,且只有优先级不低于他的才能获得执行机会。更详细区别如下:
5.改变线程优先级
1).线程优先级越高的,机会越多。比如,三个线程start,他们都输出自己的名字,那么在相同时间内,优先级最高那个输出的名字是最多的。
2).设置和获取优先级:setProperty(int n)、getProperty(int n);
3).优先级具体有哪些:上面的n在【1,10】,但一般用常量:Thread.MAX_PRIORITY、Thread.NORM_PRIORITY(main线程和默认创建时候的优先级)、Thread.MIN_PRIORITY
代码
public static void main(String[] args) {
Thread threadMax=new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("max");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread threadMin=new Thread(new Runnable() {
@Override
public void run() {
while (true){
System.out.println("min");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
threadMax.setPriority(Thread.MAX_PRIORITY);
threadMin.setPriority(Thread.MIN_PRIORITY);
threadMax.start();
threadMin.start();