线程合并
- 线程中join方法的意思是把指定的线程加入到当前线程,即将两个交替执行的线程合并为顺序执行的线程。比如在主线程B中,子线程A调用了join()方法,意思是说直到线程A执行完毕后,线程B才会继续执行。同理,如果子线程A调用了join(10)方法,意思是说等线程A执行10毫秒后,线程B才会继续执行;
- 合并线程是加入到启动线程的这个线程里,主线程等待加入线程执行完执行。
代码展示:
package edu.xalead;
//class T4 implements Runnable{
// @Override
// public void run() {
//
// while(true){
// System.out.println(Thread.currentThread().getName());
// }
// }
//}
class T9 extends Thread{
T9(){
/*super*/this.setName("合并线程"); //给线程起名字
}
@Override
public void run() {
while(true){
System.out.println(this.getName());
}
}
}
public class 加入 {
public static void main(String[] args)throws InterruptedException {
// Thread t = new Thread(new T4());
// t.start();
T9 t1 = new T9();
t1.start();
//t1.join();
//t.join(); //主线程等着t线程执行完
while(true){
System.out.println(Thread.currentThread().getName());
}
}
运行结果:
主线程和T9线程执行概率各位1/2
线程的优先级:
优先级高则获得执行时间多,相反若优先级低则获得的执行时间少。
运行代码:
package edu.xalead;
class TS implements Runnable{
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName());
}
}
}
public class 线程的优先级 {
public static void main(String[] args) {
Thread t = new Thread(new TS(),"A");
Thread t1 = new Thread(new TS(),"B");
Thread t2 = new Thread(new TS(),"C");
t.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.NORM_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t.start();
t1.start();
t2.start();
//优先级在start之后使用没有作用,须在Start之前使用
}
}
运行结果:
执行顺序是A,B,C.