加入线程
程序员文章站
2022-03-05 16:54:06
...
其他线程要等待这个调用join()方法的线程死亡即终止,才可抢占cpu。
场景:模拟下载电影
package com.commons.commons.testthread;
/**
* @Author zhaomengxia
* @create 2019/10/15 9:57
*/
public class ThreadDemo extends Thread{
private String name;
public ThreadDemo(String name) {
super(name);
this.name = name;
}
@Override
public void run() {
for (int i = 1; i <=100 ; i++) {
System.out.println(this.name+"下载了:"+i+"%");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
调用join()。如下图 。其他线程要等待这个调用join()方法的线程死亡即终止,才可抢占cpu。
package com.commons.commons.testthread;
/**
* @Author zhaomengxia
* @create 2019/10/15 9:59
*/
public class ThreadDemoTest {
public static void main(String[] args) {
ThreadDemo threadDemo=new ThreadDemo("电影1");
ThreadDemo threadDemo1=new ThreadDemo("电影2");
ThreadDemo threadDemo2=new ThreadDemo("电影3");
threadDemo.start();
//这个的位置,必须放在所要加入的线程启动之后和下一个线程启动之前
try {
threadDemo.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
threadDemo1.start();
threadDemo2.start();
}
}
结果
上一篇: Drf 序列化 ModelSerializer跨表取数据
下一篇: 会用ps就会用ai吗