[javaSE] 多线程(join方法)

时间:2022-01-06 06:32:20

多条线程并发执行,随机切换,调用join()方法,会使当前线程所在的线程(一般主线程)冻结,直到当前线程结束,所在的线程才恢复继续执行

class JoinTestDemo implements Runnable{

    @Override
public void run() { for(int x=0;x<=5;x++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"===="+x);
}
} }
public class JoinDemo { /**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
JoinTestDemo join=new JoinTestDemo();
Thread t1=new Thread(join);
Thread t2=new Thread(join);
t1.start();
t2.start();
//上面两个子线程交替执行,主线程冻结,t1走完才解冻
t1.join();
//显示主线程
for(int x=0;x<=5;x++){
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"===="+x);
}
} }

[javaSE] 多线程(join方法)

线程的优先级,调用Thread对象的setPriority()方法,可以设置优先级,参数:1,5,10最明显;Thread.MAX_PRIORITY,Thread.MIN_PRIORITY,Thread.NORM_PRIORITY

调用Thread.yield();可以暂时释放执行权,达到线程平均运行的目的